[英]Not sure why 1 printf statement prints twice
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! 我以为这个代码块给我两次打印printf语句时出错,但是我注释掉了代码中的所有内容,并且一切正常! What seems to be the issue then is the work I am doing with process IDs.
那么,问题似乎出在我正在使用进程ID进行的工作中。 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? 子进程的父进程可能会第二次打印该序列吗?
Yes, once the parent process has wait()
ed on the child process, it continues down the code path and prints the sequence. 是的,一旦父进程对子进程进行了
wait()
处理,它将继续沿代码路径向下并打印序列。
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);
}
After 后
wait(NULL);
You need an exit/return. 您需要退出/返回。 The parent has done its job of bringing up the child and is done
父母已经完成了抚养孩子的工作,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.