子进程不会因kill(pid_t, SIGTERM)而死亡

标签 c linux process fork

我正在用 C 进行编码,并尝试 fork 一个服务器,该服务器接受从客户端到其自己进程的连接,但是,在我使用命令行参数终止它后,该服务器仍然继续接受指定端口上的连接。

pid_t server_id;

 int spawn(char* func, char** argl)
{
    pid_t cid;
    cid = fork();
    server_id = cid;
    if(cid!=0)
        return cid;
    else
    {
        execvp(func, argl);
        int errcode = errno;
        fprintf(stderr, "Error reached: %s\n",strerror(errcode));
        abort();
    }

}

...

int main (int argc, char* argv[])
{
    //stuff

    do{
        next_option = getopt_long (argc, argv, short_options,long_options, NULL);
        switch (next_option)
        {
            case 'h':   /* -h or --help */
                print_usage (stdout, 0);

            case 's':  ; /* -s or --start-server */
                char* arglist[] = {"server",argv[2],NULL}; //argv[2] is the port number
                spawn(server_path,arglist);
                break;

            case 'x':   /* -t or  --transport */
                kill(server_id,SIGTERM);
                printf("SERVER TERMINATED\n");
                break;

        //more stuff

    return 0;
}

server.c 是一个多线程服务器,可以接受来自多个客户端的连接。我没有包含它的代码,因为我相信当终止一个进程时,它的线程会随之被杀死?

最佳答案

因为子pid在父函数中没有持久化,而子函数恰好是监听端口的服务器,所以我正在这样做

strcpy(command,"lsof -t -i:"); //get pid of process listening to port number
strcat(command,argv[2]); //concatenate port
in = popen(command,"r");
fgets(temp,5,in); //save output from running command
printf("%s\n",temp);
server_id = atoi(temp);
fprintf(stderr, "TERMINATING server %d\n", server_id);
kill(server_id,SIGTERM);
printf("SERVER TERMINATED\n");

关于子进程不会因kill(pid_t, SIGTERM)而死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45850922/

相关文章:

c++ - 如何获取传递给正在运行的进程的命令行参数?

linux - Ubuntu/usr/bin/ld : cannot find -lsasl2 while installing monary

perl - 一种估计程序运行时间的算法

c++ - 为什么在 C++ 头文件中使用 #ifndef 和 #define?

c - C中将节点插入有序链表

c - 使用 waitpid() 的例子?

linux - 在 Makefile 命令中设置变量

c - 在没有 root 权限的情况下实现共享内存

node.js - Nodejs获取相对于process.cwd()的绝对路径

process - 当你在 Unity 中按下 "play"按钮时到底会发生什么?