CTRL-C不会杀死程序linux / C.

时间:2018-03-20 19:54:34

标签: c unix fork

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

如果我有这样的程序

char *args = "echo hey";

pid_t pid = fork();
if(pid == 0) {
    while(1) {
        pid2 = fork();
        wait(NULL);
    }
}

Ctrl c没有查杀程序,如何让ctrl-c阻止孩子运行?

1 个答案:

答案 0 :(得分:3)

当第一个孩子进入无限循环时,启动代码的父进程可能会退出,因此孩子不再接收键盘输入。

您需要让父进程等待第一个子进程来保持父进程:

if(pid == 0) {
    while(1) {
        pid2 = fork();
        if(pid2 == 0) {
            execlp("sh", "sh", "-c",args, (char *)NULL);
            perror("sh");
            return(1);
        }
        wait(NULL);
    }
} else {
    wait(NULL);
}