我目前正在編寫一個簡單的shell在C中,我面臨的信號問題。處理信號sigtstp - sigcont - sigint與子進程在C
例如,當我啓動我的程序時,我鍵入ping命令,然後鍵入CTRL-Z我希望子進程(ping命令)暫停,然後在我使用fg時回來。
我認爲我需要存儲一個全局變量執行ping命令的子pid。
我已經檢查了其他帖子來解決我自己的問題,但我無法得到它的工作。
這是執行命令(多個命令| |)和存儲子pid的代碼。
int exec_proc(int input, int output, char** command) {
pid_t runner;
runner = fork();
f_pid = runner;
if (runner == 0) {
// Use input for stdin
if (input != 0) {
dup2(input, 0);
close(input);
}
// Use output for stdout
if (output != 1) {
dup2(output, 1);
close(output);
}
// Return command code
execvp(command[0], command);
}
// An error occured
return -1;
這是我的處理程序c文件。
pid_t f_pid;
/**
* Handles every handler !
*/
void handlerManager()
{
signal(SIGINT,INTHandler);
signal(SIGTSTP,TSTPHandler);
signal(SIGCONT,CONTHandler);
}
/**
* Handler for CTRL-C
* @param sig
*/
void INTHandler(int sig)
{
printf("\nDo you really want to quit ? [y/n] \n");
int answer = getchar();
if(toupper(answer) == 'Y')
kill(f_pid,SIGINT);
}
/**
* Handler for CTRL-Z (processus sleep)
* @param sig
*/
void TSTPHandler(int sig)
{
printf("\nGoing to sleep! \n");
printf("%d", f_pid);
kill(f_pid,SIGTSTP);
}
/**
* Handler to reset a processus
* @param sig
*/
void CONTHandler(int sig)
{
printf("\nHey i'm awake\n");
kill(f_pid,SIGCONT);
}`
當我打印PID時,我得到正確的PID。
最後這個地方我打電話給我的處理程序管理器。
int main() {
char* line;
char** args[MAX_ARG_SIZE] = {NULL};
int status;
handlerManager();
do {
fflush(stdin);
prompt();
line = readline();
char linecpy[strlen(line)];
strcpy(linecpy, line);
splitBy(line, " ", args);
status = exec(args, linecpy);
switch (status) {
case EMPTY_LINE:
break;
}
} while (status);
return 0;
在此先謝謝您,並對我的英語感到抱歉。
嗨,謝謝你的回答我做了更改,但是當我在命令中按Ctrl-Z時,它確實改變了processus的狀態,但是當我鍵入fg時,我在子進程(ping命令) 。 –
請參閱編輯。 –