使用C创建子进程和父进程

使用C创建子进程和父进程,c,linux,compilation,fork,C,Linux,Compilation,Fork,我正在用C编写以下代码。我正在编写一个程序,使用fork系统调用创建一个新进程。然后我想检查哪一个是活动的,最后它是否是子进程,返回该文件中所有目录的列表,或者它是否是父进程,等待子进程终止 以下是我的代码: #include <stdio.h> #include <string.h> #include <dirent.h> #include <iostream> int main(){ int pid = fork(); if(pi

我正在用C编写以下代码。我正在编写一个程序,使用
fork
系统调用创建一个新进程。然后我想检查哪一个是活动的,最后它是否是子进程,返回该文件中所有目录的列表,或者它是否是父进程,等待子进程终止

以下是我的代码:

#include <stdio.h>
#include <string.h>
#include <dirent.h> 
#include <iostream>


int main(){
  int pid = fork();
  if(pid < 0){
    printf(stderr, "Fork call failed! \n");
  }
  else if(pid == 0){
    printf("This process is the child from fork=%d\n", pid);
    printf("Thecurrent file inside the directory are:\n");
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d) {
      while ((dir = readdir(d)) != NULL) {
    printf("%s\n", dir->d_name);
      }
      closedir(d);
    }
    exit(0);
  }
  else{
    printf("This process is the parent from fork=%d\n", pid);
    int stats;    
    //parent process waits for child to terminate
    waitpid(pid, &stats, 0);

    if(stats == 0){
      printf("This process is terminated.");
    }

    if(stats == 1){
      printf("This process is terminated and an error has occured.");
    }
  }
  return 0;
}

如何解决此问题?

您的错误出现在对
printf()
的第一个函数调用中:

它实际上应该是
fprintf()

fprintf(stderr, "Fork call failed! \n");

此外,不要忘记包括:

  • unistd.h
    用于
    fork()
  • sys/types.h
    sys/wait.h
    用于
    waitpid()
  • stdlib.h
    用于
    exit()

<> >删除>代码>包含<代码>,因为这是用C++ C++编写的C++库,抱歉我用C++库来做这个错误吗?C@FedericoklezCulloca我明白了,okiI会删除它,但我如何确保下一个错误不会发生?你是如何编译的?您没有告诉。1_3.c:12:5:警告:从不兼容的指针类型[默认情况下启用]传递'fprintf'的参数1。您只是将第一个
printf()
替换为
fprintf()
?@S.N。您只需要将第一个printf替换为fprintf。是的,它只是第一个(即:取
stderr
)@S.N.编译问题解决了。如果您还有其他问题,请发布其他问题。
fprintf(stderr, "Fork call failed! \n");