c - 在函数中调用 fork() 后主进程不打印

标签 c linux unix process fork

我正在尝试编写一个 shell,但我不明白为什么 createProcess 函数结束后主进程没有打印此 "> "。 还有更好的方法来仅从主进程打印一些东西吗?我使用了这个 if (mainPid == getpid()

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void createProcess(){
   pid_t  pid;
   pid = fork();
   if (pid == 0){
      printf("Process created\n");
      printf("Child pid is %d\n", getpid());
   }
}

char *read_line(){
   char *line = NULL;
   size_t bufsize = 0;
   getline(&line, &bufsize, stdin);
   return line;
}

int main(){
   pid_t mainPid = getpid();
   char* line = NULL;
   for (;;) {
      if (mainPid == getpid()){
         printf("> ");
         line = read_line();
         if (line[strlen(line) - 1] == '\n')
            line[strlen(line) - 1] = '\0';
         if (strcmp(line, "create") == 0)
            createProcess();
         else printf("Write \"Create\"\n" );
      }
   }
free(line);
return 0;
}  

预期输出

> create
Process created
Child pid is 2417
> 

最佳答案

> create

> Process created

Child pid is 5655

所以我测试了它并得到了这个^(注意“进程创建”之前的“>”)。 这意味着它不是按照您想要的顺序打印出来的。

编辑这是一个修复:

void createProcess(){
      pid_t  pid;
      pid = fork();
      if (pid == 0){
         printf("Process created\n");
         printf("Child pid is %d\n", getpid());
         exit(0);
      }
      if (pid > 0) {
         int stat_loc;
         wait(&stat_loc);
      }
   }

得到这个输出:

> create
Process created
Child pid is 5700
> 

关于c - 在函数中调用 fork() 后主进程不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891745/

相关文章:

PHP5.3(作为Apache模块)无法写入/var/www/<project-name>/<document-root>/cache

regex - 使用 sed 替换等长文本

bash - 第三方二进制文件应该安装在 UNIX 系统上的哪里?

mysql - mysql_insert_id 线程安全吗?

linux - 解压终端所有子目录下的所有gz文件

django - 为什么 nginx 接受主机 header 与 server_name 不匹配的请求?

bash - shell编程中的命令 "grep | cut"

c - 将 char 附加到没有值的字符串

c - 为什么 __sync_add_and_fetch 在 32 位系统上对 64 位变量起作用?

C: 如何用 makefile 编译包含在另一个头文件中的头文件?