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

标签 c linux compilation fork

我正在用 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;
}
fatal error: iostream: No such file or directory  #include <iostream>
                    ^ compilation terminated.

如果我删除 #include <iostream> ,我得到:

/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘struct _IO_FILE *’

我该如何解决这个问题?

最佳答案

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

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

其实应该是fprintf()相反:

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

此外,不要忘记包括:

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

并删除 #include <iostream>因为那是针对 C++ 的。

关于c - 使用 C 创建子进程和父进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027904/

相关文章:

c - 如何更新 includePath. #include 检测到的错误

c++ - Shell/Makefile 链接器

c - 如何将 ELF 可执行文件转换为 C 代码?生成的 C 代码不需要是人类可读的

linux - 不同进程的 %cpu 通过 busybox 和 procps-ng 的 top 输出

c++ - 使用 fsyntax-only 参数切换警告

c - 尝试使用 argv 在 C 中获取字符计数频率?

c - 带返回终止符的 void 函数

linux - wget 另一个服务器文件夹中的最新文件

c++ - GDB - 未找到调试符号 -

c++ - 警告 : type qualifiers ignored on function return type [-Wignored-qualifiers]