代码之家  ›  专栏  ›  技术社区  ›  S. N

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

  •  2
  • S. N  · 技术社区  · 6 年前

    我正在用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 *’
    

    如何解决此问题?

    1 回复  |  直到 6 年前
        1
  •  6
  •   JFMR    6 年前

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

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

    实际上应该是 fprintf() 而是:

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

    此外,不要忘记包括:

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

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