【CO004】操作系统实践笔记4 —— Linux 常用 System Call

笔者:YY同学

生命不息,代码不止。好玩的项目尽在GitHub



fork(),getpid() 和 getppid()

  • 描述:
    fork() 用于进程创建,子进程会复制所有父进程的变量,类似于克隆(clone)。两个进程之间相互独立,可以各自做自己的事情。getpid() 返回当前进程的 pid 值,getppid() 返回当前进程父进程的 pid 值。

  • 函数原型:
    pid_t fork(void);
    无输入参数,pid_t 可以看作是一个整型返回值,表示进程的 pid。
    pid_t getpid(void);
    无输入参数,返回当前进程 pid。
    pid_t getppid(void);
    无输入参数,返回当前进程父进程的 pid。

  • 必要头文件:
    #include <unistd.h>

  • 核心代码:

#include<stdio.h>
#include<unistd.h>

int main(){

    int pid_child = fork();
    
    if(pid_child!=0){
        printf("Parent process with PID: %d\n", getpid());
    }
    else{
        printf("Child process with PID: %d\n", getpid());
    }
    
    return 0;
}

exec() 族

  • 描述:
    在 Linux 中可以把终端(terminal)执行的命令放到 C 语言的代码中执行。exec() 执行之后该进程下的代码块会被它整个替换,声明的变量和存储的数据结构都会消失,但是进程仍然保留 pid 和 running time,就好比壳还是原来的进程,但是里面已经完全变成另一个东西了。因为 exec() 的替换性,在执行 exec() 之前一般需要用 fork 创建子进程,然后在子进程下执行,以避免父进程被替换导致之前的数据丢失。

  • 必要头文件:
    #include <unistd.h>

  • 语法速记:
    在这里插入图片描述

  • 核心代码:

  1. execl
execl("/bin/ls", "/bin/ls", "-l", "-a", NULL);
  • 第一个参数表示路径,需要使用绝对路径,要记得加 /bin
  • 使用参数列表,一个参数一个引号
  • 结尾记得加 NULL
  1. execlp
execlp("wc", "wc", "-l", NULL);
  • 第一个参数表示路径,需要使用相对路径,可以没有 /bin
  • 使用参数列表,一个参数一个引号
  • 结尾记得加 NULL
  1. execv
char* cmd_argv[4];
cmd_argv[0] = "/bin/cowsay";
cmd_argv[1] = "-y";
cmd_argv[2] = "good morning"; 
cmd_argv[3] = NULL;   

execv(cmd_argv[0], cmd_argv);
  • 第一个参数表示路径,需要使用绝对路径,要记得加 /bin
  • 使用参数 array,将所有参数写入 array
  • 数组最后一位是 NULL
  1. execvp
char* cmd_argv[4];
cmd_argv[0] = "cowsay";
cmd_argv[1] = "-y";
cmd_argv[2] = "good morning"; 
cmd_argv[3] = NULL;   

execvp(cmd_argv[0], cmd_argv);
  • 第一个参数表示路径,需要使用相对路径,可以没有 /bin
  • 使用参数 array,将所有参数写入 array
  • 数组最后一位是 NULL
  1. execle
char* binaryPath = "/bin/bash";
char* arg1 = "-c";
char* arg2 = "echo \"Visit $HOSTNAME:$PORT from your browser.\"";
char *const env[] = {"HOSTNAME=www.linuxhint.com", "PORT=8080", NULL};

execle(binaryPath, binaryPath, arg1, arg2, NULL, env);
  • 参考 execl 方法
  • 注意最后一个参数需要添加 env 数组
  1. execve
char *binaryPath = "/bin/bash";
char *const args[] = {binaryPath, "-c", "echo \"Visit $HOSTNAME:$PORT from your browser.\"", NULL};
char *const env[] = {"HOSTNAME=www.linuxhint.com", "PORT=8080", NULL};

execve(binaryPath, args, env);
  • 参考 execv 方法
  • 注意最后一个参数需要添加 env 数组

wait() 与 waitpid()

  • 描述:
    用于阻塞当前进程,直至符合条件的进程结束后结束阻塞。一般用于已创建子进程的父进程当中,这样可以保证父进程在子进程结束之后结束。

  • 函数原型:
    pid_t wait(int* status);
    输入一个状态参数,记录 wait() 执行时的状态。
    pid_t waitpid(pid_t pid, int* status, int options);
    在 wait() 基础上增加了 pid 参数,表示只该 pid 的进程进行等待,option 参数不常用,一般为 0。

  • 必要头文件:
    #include <sys/types.h>
    #include <sys/wait.h>

  • 核心代码:

int pid1 = fork();
int pid2 = fork();

// parent process
if(pid1!=0 && pid2!=0){
    wait(NULL); // 父进程阻塞,直至任意一个子进程结束后消除阻塞,程序退出
    exit(0);
}
int status = 0;
int pid1 = fork();
int pid2 = fork();

// parent process
if(pid1!=0 && pid2!=0){
    waitpid(pid1, &status, 0); // 父进程阻塞,直至pid1的子进程结束后消除阻塞,程序退出
    exit(0);
}
  • 宏定义的 status 检测函数(返回值为 bool,是返回 True,不是返回 False)
    1. WIFEXITED(status):子进程正常退出。
      WEXITSTATUS(status):子进程退出时返回代码。

    2. WIFSIGNALED(status):子进程由于未捕捉到信号而退出,属于异常退出。
      WTERMSIG(status):子进程捕捉到信号并给出信号的值。

    3. WIFSTOPPED(status):子进程当前处于停止态。
      WSTOPSIG(status):子进程捕捉到停止信号并给出信号的值。

    4. WIFCONTINUED(status):子进程当前处于继续运行状态


signal() & kill() & alarm()

  • 描述:
    signal() 用于设置信号响应函数,其表现为当接收到某种信号后立刻调用某个函数事件,在 Linux 下,signal() 也是一种 system call。kill() 用于发送不同的信号量给对应 PID 的进程,所以二者一般配合使用。alarm() 一般配合 SIGALRM 信号出现,表示在 n 秒后向进程发送一个 SIGALRM 信号。

  • 函数原型:
    sig_t signal(int signum,sig_t handler);
    第一个参数表示信号参数,如 SIGINT、SIGTERM,第二个参数表示一个无返回值的函数的指针。可以是调用函数的指针,也可以是 SIG_IGN(忽略该信号)和 SIG_DFL(默认处理该信号)。
    int kill(pit_t pid,int sig);
    向进程号为 pid 的进程发送信号参数。
    unsigned int alarm(unsigned int seconds);
    输入一个无符号整型值,表示经过 seconds 秒后会向当前进程发送一个 SIGALRM 信号。

  • 必要头文件:
    #include <sys/types.h>
    #include <signal.h>

  • 常用信号量及其含义

SignalMeaning
SIGINTInterrupt 中断信号,中断进程,一般由用户通过键盘 Ctrl+C 发送
SIGQUITQuit 退出信号,退出时会产生core文件, 类似于一个程序错误信号,由 Ctrl+\ 发送
SIGTERMTerminate 终止信号,结束进程,一般通过 kill() 发送,能否成功需要看当前进程状态(一般僵尸态是无法用 kill() 终止的)
SIGTSTP暂停信号,将进程挂起,可以由用户通过键盘 Ctrl+Z 发送,也可以用 kill() 发送
SIGSTOPStop 暂停信号,与 SIGTSTP 效果相似,暂时停止进程运行(注意不是结束进程),该信号不能被忽略和阻塞
SIGCONTContinue 继续信号,将挂起进程接触挂起,继续运行
SIGALRMAlarm 闹钟信号,一般由 alarm() 发送给进程
SIGCHLD当子进程发生任何信号事件(挂起、继续、退出、强制结束)时给父进程发送信号
SIGKILL终极杀器,强制结束进程,一定成功,慎用
  • 核心代码:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>

#define TIMEOUT 5

int child_pid=0;

void sig_handler(int sig){
    kill(child_pid, SIGCONT);
}

int main(){

    printf("Parent: 0 sec: Child is ready!\n");
    sleep(1);

    child_pid = fork();
 
    if(child_pid == 0){
            
        kill(getpid(), SIGTSTP);  // 发送 TSTP 暂停信号

        printf("Child: continuing to run\n");
        
        int j;
        for(j = 1; j <= 10; ++j){
             printf("%d ", j);
             sleep(1);
             fflush(stdout);
        }
         
        printf("\n");
        printf("The child is dead!\n"); 
       
    }
    else{
       
        signal(SIGALRM, sig_handler);  // 设置 signal 信号,当发送 SIGALRM 信号时调用函数sig_handler
        alarm(TIMEOUT);
        int i;

        for(i = 1; i <= TIMEOUT; ++i){
            printf("%d sec: waiting ...\n", i);
            sleep(1);
        }
        
        int status;
        waitpid(child_pid, &status, 0);

        printf("The father is dead!\n");
    }

    return 0;
}

文件操作

  1. int open(const char *pathname, int flags);
    int open(const char *pathname, int flags, mode_t mode);
  • 描述:open() 用于打开文件。pathname 为打开文件路径,flag 为文件打开标记(如文件不存在时自动创建等),mode 为文件操作权限(如只读、只写、读写等)。
  • 头文件:#include<fcntl.h>
  1. int creat(const char *pathname, mode_t mode);
  • 描述:creat() 只能以写的方式打开文件,功能上基本等于 open()。
  • 头文件:#include<fcntl.h>
  1. int close(int fd);
  • 描述:关闭一个已经打开的文件,对应 open() 和 creat()。
  • 头文件:#include <unistd.h>
  1. ssize_t read(int fd, void * buf, size_t count);
  • 描述:read() 用于读入文件,并将读入数据记录在一个定长的 buffer 里。如果读取成功,返回读取的字节数;如果出错,返回 -1 并设置 errno;如果在调 read 函数之前已是文件末尾,则返回 0。
  • 头文件:#include <unistd.h>
  1. ssize_t write(int fd, const void * buf, size_t count);
  • 描述:write() 用于写入文件,将读一个定长的 buffer 里的数据写入文件流中。如果写入成功会返回实际写入的字节数;当有错误发生时则返回 -1,错误代码存入 errno 中。
  • 头文件:#include <unistd.h>

dup() 和 dup2()

  • 描述:
    dup() 和 dup2() 都是用来复制文件描述词(File Descriptor)的,通过复制 fd 来实现的文件的复制。

  • 函数原型:
    int dup(int oldfd);
    dup() 用来复制参数 oldfd 所指的文件描述词,并将它返回。此新的文件描述词和参数 oldfd 指的是同一个文件,共享所有的锁定、读写位置和各项权限或旗标。当复制成功时,则返回最小及尚未使用的文件描述词;若有错误则返回 -1,errno 会存放错误代码。
    int dup2(int odlfd, int newfd);
    dup2() 用来复制参数 oldfd 所指的文件描述词,并将它拷贝至参数 newfd 后一块返回。若参数 newfd 为一已打开的文件描述词,则newfd 所指的文件会先被关闭。dup2()所复制的文件描述词,与原来的文件描述词共享各种文件状态,dup2() 相当于调用 fcntl(oldfd, F_DUPFD, newfd)。

  • 必要头文件:
    #include <unistd.h>

  • 核心代码:

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>

int main(){

    char* q1_argv[4];
    q1_argv[0] = "/bin/cowsay";
    q1_argv[1] = "-y";
    q1_argv[2] = "good morning"; 
    q1_argv[3] = NULL;   

    int fd = open("output.txt", O_CREAT|O_APPEND|O_RDWR, 0666); // 0666 表示所有用户都只可读写
    dup2(fd, 1);
    execvp(q1_argv[0], q1_argv);

    return 0;
}

pipe()

  • 描述:
    pipe 俗称管道,用于进程之间的信息传递。因为进程之间是变量独立的(虚拟内存除外),在变量不共享的情况下要实现参数传递,管道是一个很好的工具。

  • 函数原型:
    int pipe(int fd[2]);
    输入一个 fd 的二维数组,定义 2 个文件描述符,一般 fd = 0作为标准输入流,fd = 1 作为标准输出流,fd = 2 作为标准错误流。所以为了方便记忆,我们一般会让 index = 0 的管道作为标准输入,index = 1 的管道作为标准输出。

  • 必要头文件:
    #include<unistd.h>

  • 核心代码:

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>

int main(){
    
    int p[2];

    pipe(p);
        
    if(fork() == 0){ /*child process*/
        close(p[1]);
        dup2(p[0],0);  // dup2 复制标准输入流的文件描述符,将 p[0] 定义为标准输入
        close(p[0]);

        execlp("wc", "wc", "-l", NULL);
    }
    else{ /*parent process*/
        close(p[0]);
        dup2(p[1],1);  // dup2 复制标准输出流的文件描述符,将 p[1] 定义为标准输出
        close(p[1]);
              
        execlp("who","who", NULL);
    }

    wait(NULL);
    return 0;
}

stat(),lstat(),和 fstat()

  • 描述:
    用于文件信息的查询,例如大小、状态等。

  • 必要头文件:无

  • 核心代码:

int main(int argc, char **argv) {
    struct stat file_stat;
    if( stat(argv[1], &file_stat) == -1)
        exit(1);

    printf("file size of \"%s\" = %d bytes\n",argv[1],file_stat.st_size);
    return 0;
}

opendir(),readdir() 和 closedir()

  • 描述:
    用于打开、读取和关闭路径。

  • 函数原型:
    DIR *opendir(const char *name);
    int closedir(DIR *dir);
    struct dirent * readdir(DIR * dir);

  • 必要头文件:
    #include <sys/types.h>
    #include <dirent.h>

  • 核心代码:

int main(void) {
    DIR * dir;
    struct dirent *entry;
  
    dir = opendir("/");
       
    while ( (entry = readdir(dir)) != NULL) {
        // print the directory name
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

link(),mount() 和 umount()

  • 描述:
    link() 以参数 newpath 指定的名称来建立一个新的连接(硬连接)到参数 oldpath 所指定的已存在文件,如果参数 newpath 指定的名称为一已存在的文件则不会建立连接。mount() 挂上文件系统,umount() 解下文件系统。

  • 函数原型:
    int link(const char * oldpath, const char * newpath);
    int mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data);
    int umount(const char *target);
    int umount2(const char *target, int flags);

  • 图例:
    link()
    在这里插入图片描述
    mount()umount()
    在这里插入图片描述

  • 核心代码:

#include <unistd.h>
link("/usr/jim/memo","/usr/ast/note");

#include <sys/mount.h>
mount("/dev/floppy","/b",0);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值