gpt4 book ai didi

c - 如何创建具有不同名称的子进程

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:57 25 4
gpt4 key购买 nike

我正在使用 C,我需要创建一个名称不同于父进程的子进程(例如 child_test)如何在 Linux 中使用 fork()?

最佳答案

您可以使用 prctl为此的系统调用。它有一个可怕的界面,但如果你克服了这个问题,使用它来完成这个任务是相当直接的。这是一个最小的例子。

#include <stdio.h>      /* perror() */
#include <stdlib.h> /* NULL */
#include <sys/prctl.h> /* prctl(), PR_SET_NAME */
#include <sys/types.h> /* wait() */
#include <sys/wait.h> /* wait() */
#include <unistd.h> /* fork(), sleep() */

int
main()
{
const char * name = "it_worked";
switch (fork())
{
case 0:
if (prctl(PR_SET_NAME, (unsigned long) name) < 0)
perror("prctl()");
sleep(10);
break;
case -1:
perror("fork()");
break;
default:
if (wait(NULL) < 0)
perror("wait()");
}
return 0;
}

如果我将此程序编译为名为 a.out 的可执行文件,然后运行 ​​./a.out & ps,我可以观察到以下内容

  PID TTY          TIME CMD
7462 pts/7 00:00:00 bash
7741 pts/7 00:00:00 a.out
7742 pts/7 00:00:00 it_worked
7743 pts/7 00:00:00 ps

这表明显然“有效”。

请注意,名称的最大长度限制为 16 个字节,包括终止 NUL 字节。引用手册页:

Set the name of the calling thread, using the value in the location pointed to by (char *) arg2. The name can be up to 16 bytes long, including the terminating null byte. (If the length of the string, including the terminating null byte, exceeds 16 bytes, the string is silently truncated.)

关于c - 如何创建具有不同名称的子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com