嗨,我有一个简单的函数,在这里我创建一个子进程和父进程。
子进程假设运行dd if=/some/file of=/somedisk。
父进程假设在循环中运行(直到子存在),并发送信号子查询,这迫使子进程中的DD报告进度数据。
当然,我有一些管道,可以将stdio和stderr从子级重定向到父级。(这是我在其他功能中使用的,工作正常)
我的问题是:
一。我的书桌上什么都没有;
2.一旦我发送SIGUSR1,进程就退出了。

    if(my_pid>0) //The parent part
            {

            close(FD_pipe_stdout[1]);// Parent process closes output side of the pipe
            close(FD_pipe_stderr[1]);// Parent process closes output side of the pipe
            while(0==waitpid(my_pid, &my_pid_status, WNOHANG))
                {
                kill(my_pid, SIGUSR1);
                sleep(1);
                //read(FD_pipe_stderr[0], pipe_error,PIPE_MAX_SIZE); // Read in a string from the stderror
                //puts(pipe_error);

                }
            puts("going out");
            read(FD_pipe_stdout[0], pipe_output,PIPE_MAX_SIZE); // Read in a string from the pipe's input side

            close(FD_pipe_stdout[0]);//on the end close the other side of pipe
            close(FD_pipe_stderr[0]);//on the end close the other side of pipe
            }
   else
            {   // The child part
            close(FD_pipe_stdout[0]);/* Child process closes input side of the pipe */
            close(FD_pipe_stderr[0]);/* Child process closes input side of the pipe */
            dup2(FD_pipe_stdout[1],1); //redirect the stdout(1) to the fd_pipe and then close the sdtout
            dup2(FD_pipe_stderr[1],2);//redirect also stderr to the pipe
            system(dd if=/image.img of=/dev/sda);
            close(FD_pipe_stdout[1]); //on the end close the other side of pipe
            close(FD_pipe_stderr[1]); //on the end close the other side of pipe
            exit(0);
            }

我在屏幕上看到,家长正在走出while循环,我不明白为什么。
提前谢谢

最佳答案

system()创建一个子进程来运行指定的命令,因此您实际上有三个进程:
父进程(带循环的进程)
子进程(调用system()
dd过程
你在给子进程而不是dd进程发信号。默认情况下,SIGUSR1会导致进程退出,因此您正在杀死子进程。
要解决此问题,可以使用exec函数之一运行dd,而不是调用system()

{   // The child part
    close(FD_pipe_stdout[0]);
    close(FD_pipe_stderr[0]);
    dup2(FD_pipe_stdout[1],1);
    dup2(FD_pipe_stderr[1],2);
    execlp("dd", "dd", "if=/image.img", "of=/dev/sda", NULL);
    perror("exec failed");
    exit(1);
}

现在只有两个进程,因为子进程变成了dd进程。当父母给孩子发信号时,信号将转到DD。
注意这里有一个种族状况。父进程可以在dd启动之前发送sigusr1信号并设置其信号处理程序。为了保持健壮,你应该设法处理这个问题。

关于c - 为什么SIGUSR1杀死我的dd子进程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19433393/

10-11 23:57
查看更多