Reputation: 23
UPDATE
I thought this code block was giving me an error printing a printf statement out twice, but I commented out everything in my code BESIDES this and it worked just fine! What seems to be the issue then is the work I am doing with process IDs. Here is the entire code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid, pid1;
int n;
int temp;
int stop = 1;
if (argc == 1) {
fprintf(stderr,"Usage: ./a.out <starting value>\n");
return -1;
}
n = atoi(argv[1]);
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */
pid1 = getpid();
printf("child: pid = %d\n", pid);
printf("child: pid1 = %d\n", pid1);
}
else { /* parent process */
pid1 = getpid();
printf("parent: pid = %d\n", pid);
printf("parent: pid1 = %d\n", pid1);
wait(NULL);
}
while (n!=1) {
if (n%2 == 0) {
printf("%d, ", n);
temp = (n/2);
n = temp;
}else {
printf("%d, ", n);
temp = (3*n+1);
n = temp;
}
}
printf("1\n");
return 0;
}
The output I'm expecting is something like:
parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1
But instead I get this Output:
parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1
8, 4, 2, 1
Might a child a parent process be printing out the sequence a second time?
Upvotes: 1
Views: 194
Reputation: 59987
After
wait(NULL);
You need an exit/return. The parent has done its job of bringing up the child and is done
Upvotes: 0
Reputation: 7261
Yes, once the parent process has wait()
ed on the child process, it continues down the code path and prints the sequence.
What you want is:
// ....
else if (pid == 0) { /* child process */
pid1 = getpid();
printf("child: pid = %d\n", pid);
printf("child: pid1 = %d\n", pid1);
while (n!=1) {
if (n%2 == 0) {
printf("%d, ", n);
temp = (n/2);
n = temp;
}else {
printf("%d, ", n);
temp = (3*n+1);
n = temp;
}
}
} else { /* parent process */
pid1 = getpid();
printf("parent: pid = %d\n", pid);
printf("parent: pid1 = %d\n", pid1);
wait(NULL);
}
Upvotes: 4