不确定为什么1个printf语句打印两次

时间:2018-02-08 00:04:13

标签: c

更新

我认为这个代码块给我一个错误,打印出两次printf语句,但是我在代码BESIDES中注释了所有内容并且它运行得很好!那么似乎问题是我正在处理进程ID的工作。 这是整个代码:

#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;

}

我期待的输出类似于:

parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1

但我得到了这个输出:

parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1
8, 4, 2, 1

父母进程可能会再次打印出序列吗?

2 个答案:

答案 0 :(得分:4)

是的,一旦父进程在子进程上编辑wait(),它就会沿着代码路径继续并打印序列。

你想要的是:

// ....
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);
}

答案 1 :(得分:0)

之后

 wait(NULL);

您需要退出/退货。父母已经完成了抚养孩子的工作并完成了