473,396 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

forking a process

Hi all,

I am just wondering if something is wrong with my program. What it
bascially does is to output a fibonacci sequence base on the
command-line output. If I give a 5, it will generate the first 5
fibonacci number. The problem is, I thought the parent process will
always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the

program, it will give me "1, 2, 3, 0, 1", which is, the child process
ran first. Is there any way to make the parent goes first?

Thanks.
fix.

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
int param;
pid_t pid;
int i;
int fib_n_2 = 0;
int fib_n_1 = 1;
int fib_n;

if (argc != 2)
{
fprintf(stderr, "An integer parameter is required\n");
exit(-1);
}

param = atoi(argv[1]);

if (param < 0)
{
fprintf(stderr, "An integer > 0 is required\n");
exit(-1);
}

pid = fork();

if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid > 0) { /* Parent process */
switch(param)
{
case 0:
printf("0\n");
break;
case 1:
printf("0, 1\n");
break;
default:
printf("0, 1, ");
}
wait(NULL);

printf("end Fibonacci sequence...\n");
exit(0);
}
else if (pid == 0) { /* Child process */

/* HERE */
for (i = 2; i < param; i++)
{
fib_n = fib_n_1 + fib_n_2;
fib_n_2 = fib_n_1;
fib_n_1 = fib_n;
printf("%d, ", fib_n);
}
}
}

Nov 15 '05 #1
3 2941
fe******@gmail.com writes:
I am just wondering if something is wrong with my program. What it
bascially does is to output a fibonacci sequence base on the
command-line output. If I give a 5, it will generate the first 5
fibonacci number. The problem is, I thought the parent process will
always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the

program, it will give me "1, 2, 3, 0, 1", which is, the child process
ran first. Is there any way to make the parent goes first?


fork() is not standard C. Try comp.unix.programmer.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #2
In article <11**********************@g44g2000cwa.googlegroups .com>,
<fe******@gmail.com> wrote:
I am just wondering if something is wrong with my program. What it
bascially does is to output a fibonacci sequence base on the
command-line output. If I give a 5, it will generate the first 5
fibonacci number. The problem is, I thought the parent process will
always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the
program, it will give me "1, 2, 3, 0, 1", which is, the child process
ran first. Is there any way to make the parent goes first?
C does not define any notion of "process", so whether you can
force a particular process to "go first" or not is out of the scope
of this newsgroup. comp.unix.programming might perhaps be more
appropriate.
[OT]
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
int param;
pid_t pid;
int i;
int fib_n_2 = 0;
int fib_n_1 = 1;
int fib_n;

if (argc != 2)
{
fprintf(stderr, "An integer parameter is required\n");
exit(-1);
}

param = atoi(argv[1]);

if (param < 0)
{
fprintf(stderr, "An integer > 0 is required\n");
exit(-1);
}

pid = fork();

if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid > 0) { /* Parent process */
switch(param)
{
case 0:
printf("0\n");
break;
case 1:
printf("0, 1\n");
break;
default:
printf("0, 1, ");
}
wait(NULL);

printf("end Fibonacci sequence...\n");
exit(0);
}
else if (pid == 0) { /* Child process */

/* HERE */
for (i = 2; i < param; i++)
{
fib_n = fib_n_1 + fib_n_2;
fib_n_2 = fib_n_1;
fib_n_1 = fib_n;
printf("%d, ", fib_n);
}
}
}


You need to create a synchronization method between the two
processes, so that the child process knows when it is safe to
proceed. There are a number of different methods you can use,
including (but not limited to):

- a semaphore

- a POSIX Threads mutex

- creating a pipe() before forking, with the child waiting
with "blocking I/O" (to read input from the pipe, and with the
parent not writing to the pipe until it is safe for the child
to proceed. [Note: do not use buffered I/O for this, unless
the parent process specifically flushes the I/O stream.]

- setting up a signal handler in the child process, put the
child process to sleep, then when the parent process is ready,
have it sigqueue() to send a signal to the child process to wake
the child up. However, proper operation of this depends on the
parent waiting long enough for the child to establish the signal
handler, which is tricky because the child is not certain to run
within any particular length of time. So you might have to
establish the signal handler -before- forking, and then rely
upon signal inheritence. Unfortunately, native signal inheritence
differs between System V and BSD derived Unixes, so for portability
you need to use the POSIX signal handling layer (e.g., sigaction(),
sigqueue() -- *not* kill() !)

- create and initialize a volatile variable before the fork(). In the
child, go into a loop of waiting and then testing to see whether
the volatile variable is still the initial value, looping back to
wait more if it is. In the parent, once the parent processing is
complete, and before the wait() or waitpid(), set the volatile
variable to the alternate value.
These methods all have a common flaw, which is that none of them
can force the underlying operating system to run the code for
the parent process. The operating system might decide for some reason
to wait around for the child to "do something" before allowing
the parent to proceed, so the output from the parent could in theory
end up postponed rather some time. This is not particularily likely
on a Unix system, but you do not have any control over the
scheduling algorithm between processes. You might, for that reason,
choose to use POSIX Threads instead -- since threads are part of the
same process, you do have some relative scheduling control.
But proper bug-free implementations of POSIX threads are relatively
uncommon compared to fork()...
--
"This was a Golden Age, a time of high adventure, rich living and
hard dying... but nobody thought so." -- Alfred Bester, TSMD
Nov 15 '05 #3
fe******@gmail.com wrote:
# Hi all,
#
# I am just wondering if something is wrong with my program. What it
# bascially does is to output a fibonacci sequence base on the
# command-line output. If I give a 5, it will generate the first 5
# fibonacci number. The problem is, I thought the parent process will
# always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the
#
# program, it will give me "1, 2, 3, 0, 1", which is, the child process
# ran first. Is there any way to make the parent goes first?

Unless the system makes this guarentee explicitly, you should not
presume it. Generally in parallel programming, you need to use
explicit mechanisms to serialise parallel processes. Since C does
not have these mechanisms built into the grammar of language
(compared to, say, Concurrent Pascal), you need to use a library
specific to your system to serialise.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Haven't you ever heard the customer is always right?
Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Eric S. Johansson | last post by:
I was working on a filter for postfix and instead of using the "fork a new python process on every message" route, I decided to use the SMTP interface instead and try forking after having started...
1
by: SRam | last post by:
How to create a threaded process in Perl. I need explanation for this code from Advanced Perl Programming.... # Forking server use IO::Socket; $SIG{CHLD} = sub {wait ()}; $main_sock = new...
0
by: SRam | last post by:
I a writing Forking Server for a Small application.. This is code for multiplexing my $listen = IO::Socket::INET->new(Proto => 'tcp',LocalPort => 2323, Listen => 1, Reuse => 1) or die $!; ...
0
by: Roy Smith | last post by:
I'm writing a network application in C++, using CppUnit for unit testing. I'm thinking of forking a subprocess to run tcpdump in some of my unit tests to watch actual packets on the wire as they...
2
by: Sophia Cao | last post by:
Hello, I am seeking a python solution for my project. I am trying to implement an architecture where there is a server who receives incoming messages from several clients, then those messages...
3
by: Rv5 | last post by:
im trying to write a program that has one parent process and three child processes. each child process should have a child process of their own. heres a really slim version of my code: void...
3
by: czajnik | last post by:
Hi! I'm quite new to Python development. Can someone advise me a framework useful for building (pre-)forking or threaded TCP servers, other than SocketServer ? I've seen source code of a few...
10
by: qwertycat | last post by:
I'm new to multi-process programming, should one avoid forking children from children of a parent? I'd like to spawn 10 children from the parent and each of those children spawns another 5...
0
by: SteveBark | last post by:
I have a script that basically runs through an array performing various sub procedures against data. My problem is that I want the data from the array to be fed into forked processes so that I...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.