简体   繁体   English

C叉杂散工艺

[英]C Fork Stray Process

I am using fork & have a problem where if 1 branch exits, the others are left stray. 我正在使用fork&有一个问题,如果退出1个分支,则其他分支会迷路。
By "stray", I mean I am back in bash & can type in system commands, but the server is constantly outputting on top of my cursor. 所谓“杂散”,是指我回到了bash并可以键入系统命令,但是服务器一直在光标上方输出。 The code used to work by killing both branches if I ^c . 该代码以前通过杀死两个分支来工作,如果I ^ c Since adding sockets into the mix, a client disconnecting caused the server to go stray. 由于在混合中添加了套接字,因此客户端断开连接导致服务器出现故障。

Anyone have ideas as to why? 有人对为什么有想法吗?

In my main() : 在我的main()中:

printf("\n      Server Running   Press ^c to quit\n\n");

if (!fork()) { // Debug output
    while (1) {
        // Do output stuff until ^c signal
        fflush(stdout);
    }
} else { // Internets
    while (1) {
        clfd=accept(listenfd, (struct sockaddr*)&claddr, &claddrlen);
        if (!fork()) { // Listener
            close(clfd);
        } else { // Communication branch
            num=rand()%16;
            //i=recv(clfd, &num, sizeof(num), 0);
            send(clfd, &num, 1, 0);
            close(clfd);
            exit(0);
        }
    }
    exit(0);
}

return 0;

This is from ps: 这是从ps:

  PID TTY          TIME CMD
11159 pts/8    00:00:00 sv_run
11899 pts/8    00:00:00 sv_run
11987 pts/8    00:00:00 ps
21687 pts/8    00:00:01 bash

This is is part of the pstree: 这是pstree的一部分:

|-sshd---sshd---csh
|-sshd---bash---top
|-2*[sv_run]
|-8*[trashapplet]
|-udevd---udevd

When you press Control + C , you kill the process that have created multiple child processes. 当您按Control + C时 ,您将杀死已创建多个子进程的进程。 Killing the parent does not, by default, kill child processes, and therefore they continue to run while you continue working in the terminal. 默认情况下,杀死父进程不会杀死子进程,因此当您继续在终端中工作时,它们将继续运行。 And because all of the processes share the same output device, the output is interleaved. 并且由于所有进程共享同一输出设备,因此输出是交错的。

I am not sure what do you actually expect your code to do. 我不确定您实际上期望代码做什么。 Neither I know what platform you are using. 我也不知道您正在使用什么平台。 But if it so happens that you want kill the process and all of its children on SIGINT and you are using Linux, then you can ask the kernel to deliver SIGHUP upon death of the parent in your child processes. 但是,如果发生这种情况,您想杀死SIGINT上的进程及其所有子进程,并且您使用的是Linux,那么您可以要求内核在子进程中的父进程死亡后交付SIGHUP For more details on how to do this, see How to make child process die after parent exits? 有关如何执行此操作的更多详细信息,请参见如何使父进程退出后子进程死亡?

Alternative, you have to make your server kill of its child processes on exit, for example, by using a custom SIGINT signal handler . 或者,您必须使服务器在退出时杀死其子进程,例如,使用自定义SIGINT 信号处理程序

Hope it helps. 希望能帮助到你。 Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM