【问题标题】:Not sure why 1 printf statement prints twice不知道为什么 1 printf 语句打印两次
【发布时间】:2018-02-08 00:04:12
【问题描述】:

更新

我认为这个代码块给了我两次打印 printf 语句的错误,但是我在代码中注释掉了除此之外的所有内容,它工作得很好!那么问题似乎是我正在使用进程 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

父进程的子进程是否会再次打印出序列?

【问题讨论】:

  • 我尝试了您显示的代码,正如我所料,它打印了一次输出。所以你展示的没有描述的问题。但是,由于我没有看到整个 main 程序,因此您没有显示某些内容。
  • 您能给我们看一下完整代码文件吗? (它应该以#include 开头,包括int main(int argc, char **argv) 或类似名称等。)它也可能有助于了解您是如何运行文件的。
  • 这里也一样,我编译了你的代码,我只有一行。请提供minimal reproducible example
  • 好吧......因为序列第二次打印它是在一个新行上,我们可以很安全地假设它与您的 while 循环无关。三种很可能的可能性:显示的子程序执行了两次,您不小心在命令行上运行了两次程序,或者您正在打印的程序出现错误。
  • 不要使用atoi,因为它处理错误的工作很糟糕

标签: c


【解决方案1】:

是的,一旦父进程对子进程进行了wait()ed,它就会继续沿着代码路径向下并打印序列。

你想要的是:

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

【讨论】:

    【解决方案2】:

    之后

     wait(NULL);
    

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

    【讨论】: