[linux] setsid测试
Posted adream307
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[linux] setsid测试相关的知识,希望对你有一定的参考价值。
测试程序如下
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
printf("start...\\n");
int err = setenv("ENV_TEST","VALUE_TEST",0);
if(err<0) return err;
int pid = fork();
if(pid<0) return -1;
if(pid==0)
// if(setsid()<0)
// printf("child setsid error\\n");
//
for(;;)
char *env = getenv("ENV_TEST");
if(env!=NULL)
pid = getpid();
printf("child env = %s,pid = %d, pgid = %d\\n",env,pid,getpgid(pid));
else
printf("child env = null\\n");
sleep(1);
else
for(;;)
char *env = getenv("ENV_TEST");
if(env!=NULL)
pid = getpid();
printf("parent env = %s,pid = %d, pgid = %d\\n",env,pid,getpgid(pid));
else
printf("parent env = null\\n");
sleep(1);
return 0;
程序运行时在终端号打印如下信息:
$ ./detach_process
start...
parent env = VALUE_TEST,pid = 11015, pgid = 11015
child env = VALUE_TEST,pid = 11016, pgid = 11015
parent env = VALUE_TEST,pid = 11015, pgid = 11015
在当前终端按 CTRL-C
,可以发现父进程和子进程同时被终止
在子进程设置 setsid
,代码如下:
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
printf("start...\\n");
int err = setenv("ENV_TEST","VALUE_TEST",0);
if(err<0) return err;
int pid = fork();
if(pid<0) return -1;
if(pid==0)
if(setsid()<0)
printf("child setsid error\\n");
for(;;)
char *env = getenv("ENV_TEST");
if(env!=NULL)
pid = getpid();
printf("child env = %s,pid = %d, pgid = %d\\n",env,pid,getpgid(pid));
else
printf("child env = null\\n");
sleep(1);
else
for(;;)
char *env = getenv("ENV_TEST");
if(env!=NULL)
pid = getpid();
printf("parent env = %s,pid = %d, pgid = %d\\n",env,pid,getpgid(pid));
else
printf("parent env = null\\n");
sleep(1);
return 0;
程序运行时在终端号打印如下信息:
$ ./detach_process
start...
parent env = VALUE_TEST,pid = 11015, pgid = 11015
child env = VALUE_TEST,pid = 11016, pgid = 11015
parent env = VALUE_TEST,pid = 11015, pgid = 11015
此时在当前终端按 CTRL-C
,可以发现只有父进程被终止了,子进程依然在运行
以上是关于[linux] setsid测试的主要内容,如果未能解决你的问题,请参考以下文章
[Linux内核]ctrl-z/fg/bg/nohup/setsid/()与&/disown/screen