C: 用 scanf fork

标签 c linux fork scanf

我试过这段代码

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

int main(){

  int x=3;
  pid_t pid0=getpid();
  pid_t pid1=0;

  if(fork()==0){
    pid1=getpid();
  }

  if(getpid()==pid1){
    scanf("%d",&x);
    printf("%d",x);
  }

  return 0;

}

scanf 指令被完全忽略。它只打印旧的 x,即 3。有人可以向我解释这里发生了什么吗?

最佳答案

这是对您的代码的主要小修改。它会检查 scanf() 是否正常工作,调用 getpid() 的频率会降低一些,并且会更仔细地报告一些事情。此外, parent 在退出之前等待 child 退出。

示例运行(我将程序命名为 fork7):

$ ./fork7 <<< ''
Parent (32976 - child 32977)
Child (32977)
Oops! 3
Child 32977: 0x0000
$ ./fork7 <<< 99
Parent (32978 - child 32979)
Child (32979)
Read: 99
Child 32979: 0x0000
$

代码(fork7.c):

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

int main(void)
{
    int x = 3;
    pid_t pid1;

    if ((pid1 = fork()) == 0)
    {
        printf("Child (%d)\n", (int)getpid());
        if (scanf("%d", &x) != 1)
            printf("Oops! %d\n", x);
        else
            printf("Read: %d\n", x);
    }
    else
    {
        int corpse;
        int status;
        printf("Parent (%d - child %d)\n", (int)getpid(), (int)pid1);
        while ((corpse = wait(&status)) > 0)
            printf("Child %d: 0x%.4X\n", corpse, status);
    }

    return 0;
}

关于C: 用 scanf fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677682/

相关文章:

c - VC++中同一项目的两个c文件之间传递值

c - 基于 'C' 的 Web 应用程序框架,如 Tornado 或 Twisted?

linux - 安装 libxcb - 未找到包 'xcb-proto'

c - 需要 libudev 建议

unix - 当第一个子进程退出,然后父进程退出而不调用 wait 时会发生什么?

c - 如何运行这个程序?

Malloc 的 C 替代方案

c - 从 strtok() 获取零长度字符串

linux - 在 Linux 上使用 Tomee Plus 1.6.0 无法进行 Web 应用程序 Logback 日志记录

c - 所有 fork 函数的返回值有什么区别?