Linux C语言编程作业

编写一段C程序,创建一个子进程,并在子进程中运行grep -R“#!/bin/bash”/home命令,父进程在以下情况下立即终止子进程的运行(使用SIGTERM信号):

  • 延时10秒之后
  • 用户按下<Ctrl+Z>按键之后(要求覆盖默认行为)
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<stdio.h>

pid_t pid;
char* argument_list[]={
    
    "grep","-R","#\\!/bin/bash","/home",NULL};
void death_handler(int sig){
    
    
	if(kill(pid,SIGTERM)==0)
		fprintf(stderr,"\nChild killed\n");
}       

int main(int argc,char **argv){
    
    

        struct sigaction act;
        act.sa_handler=death_handler;
        sigaction(SIGTSTP,&act,NULL);
        sigaction(SIGALRM,&act,NULL);

        switch(pid=fork()){
    
    
                case -1: 
                        fprintf(stderr,"Fork fail\n"); break;
                case 0:
                        execvp("grep",argument_list);perror("exec");break;
                default:
                        alarm(10);pause();fprintf(stderr,"Parent dies.\n");     

        }

        return 0;
}

猜你喜欢

转载自blog.csdn.net/DwenKing/article/details/111401514