【问题标题】:using C to create a child and parent process使用 C 创建子进程和父进程
【发布时间】:2018-02-28 10:56:47
【问题描述】:

我正在用 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 &lt;iostream&gt;,我会得到:

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

我该如何解决这个问题?

【问题讨论】:

  • 用C++库用C写?
  • 很抱歉,我在这里使用 C++ 库犯了这个错误吗?
  • iostream 在 C 中不存在
  • @FedericoklezCulloca 我明白了,好的,我将删除它,但我如何确保不会发生下一个错误?
  • 你是如何编译这个的?你没说。

标签: c linux compilation fork


【解决方案1】:

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

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

实际上应该是fprintf()

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

另外,别忘了包括:

  • unistd.hfork()
  • sys/types.hsys/wait.h 代表 waitpid()
  • stdlib.hexit()

并删除 #include &lt;iostream&gt;,因为它适用于 C++。

【讨论】:

  • 1_3.c:12:5:警告:从不兼容的指针类型传递“fprintf”的参数 1 [默认启用]。
  • 你是不是把第一个 printf() 替换成了 fprintf()
  • @S.N.您只需将第一个 printf 替换为 fprintf。
  • 是的,这只是第一个(即:接受stderr的那个)。
  • @S.N.编译问题就解决了。如果您还有其他问题,请发布另一个问题。
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 2014-12-06
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多