Linux进程调度之信号(signal)机制

信号(signal)机制是Unix系统中最为古老的进程间通信机制,很多条件可以产生一个信号:

1、当用户按某些按键时,产生信号

2、硬件异常产生信号:除数为0、无效的存储访问等等。这些情况通常由硬件检测到,将其通知内核,然后内核产生适当的信号通知进程,例如,内核对正访问一个无效存储区的进程产生一个SIGSEGV信号

3、进程用kill函数将信号发送给另一个进程

4、用户可用kill命令将信号发送给其他进程

    #include <stdio.h>                              //当这段程序运行时,ctrl + c就无法
    #include <sys/types.h>                          //中断这个程序
    #include <unistd.h>
     #include <signal.h>
    void print(int m)
    {
        printf("helloworld!\n");
    }
     
     
    int main()
    {
        signal(2,print);
        
        while(1);
        return 0;
    }

无名管道通信:

无名管道用于父进程和子进程间的通信。

 #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/wait.h>
     
     
    int main()
    {
        pid_t pid;
     
        pid = fork();
        if(pid == -1)
        {
            perror("fork");
            exit(1);
        }
        else if(pid == 0)
        {
            sleep(1);
            char bu[32] = {0};
            int fd1 = open("wow.txt",O_RDONLY);
            if(fd1 == -1)
            {
                perror("open1");
                exit(1);
            }
            int ret1 = read(fd1,bu, sizeof(bu));
            if(ret1 == -1)
            {
                perror("read");
                exit(1);
            }
            printf("%s\n",bu);
        }
        else
        {    
            int  status;
            char buf[32] = "helloworld!";
            int fd = open("wow.txt",O_WRONLY |O_CREAT | O_EXCL,S_IRWXU);
            if(fd == -1)
            {
                perror("open");
                exit(1);
            }
            int ret = write(fd, buf, strlen(buf));
            if(ret == -1)
            {
                perror("write");
                exit(1);
            }
            wait(&status);    
            close(fd);
     
        }
     
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/x18261294286/article/details/81748265
今日推荐