[英]use fork (process) instead of pthread to acieve the same
我通过创建并行线程实现了以下代码的并发性。 但是,我应该如何使用 fork() 创建子进程并执行与下面的 main() 相同的工作? 我想避免创建任何线程。
struct function_args
{
pthread_t thread;
char *command;
};
int main()
{
while (1)
{
if (mode == 1)
printf("$> ");
if ((nread = getline(&line, &linecap, in)) > 0)
{
char *command;
int commands_num = 0;
struct function_args args[BUFF_SIZE];
// remove newline character
if (line[nread - 1] == '\n')
line[nread - 1] = '\0';
char *temp = line;
while ((command = strsep(&temp, "&")) != NULL)
if (command[0] != '\0')
{
args[commands_num++].command = strdup(command);
if (commands_num >= BUFF_SIZE)
break;
}
for (size_t i = 0; i < commands_num; i++)
if (pthread_create(&args[i].thread, NULL, &parseInput, &args[i]) != 0)
printError();
for (size_t i = 0; i < commands_num; i++)
{
if (pthread_join(args[i].thread, NULL) != 0)
printError();
if (args[i].command != NULL)
free(args[i].command);
}
}
else if (feof(in) != 0)
{
atexit(clean);
exit(EXIT_SUCCESS); // EOF
}
}
return 0;
}
我知道pid = fork()
返回一个 processid,对于孩子来说它是 0,对于父母来说是 >0。 但是,在下面我处理多个argv
的 for 循环中,我不确定如何翻译我的 main() 来这样做。
这真的取决于你在做什么。 一般来说,您可以执行以下操作:
for (size_t i = 0; i < commands_num; i++)
{
pid_t pid = fork();
if (pid == 0)
{
parseInput(&args[i]);
exit(0);
}
else if (pid == -1)
printError();
else
args[i].thread = pid;
}
子进程独立于父进程和 go 来完成他们的任务,因此可能不需要在此处执行等效于pthread_join()
的操作,在这种情况下将是waitpid()
,除非父进程必须等待他们的产品用它做点什么。
说到这一点,一旦进程被分叉,它们就不再共享相同的 memory 空间,因此在子进程和父进程之间传输信息本身可能是一个挑战。 如果您只是将内容打印到stdout
,则设置为 go,否则您必须找出管道以使父子通信。
使用系统本机线程(或特别是 pthreads)的另一种替代方法是使用一些绿色线程库,例如libdill ,理论上它即使在不支持本机多线程的系统中也可以启用多线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.