Linux 中部分系统的调用的简单笔记。
# 系统调用简表
该表来自 xv-6 讲义 Figure 1-2.
System call | Description |
---|---|
int fork() | Create a process, return child’s PID. |
int exit(int status) | Terminate the current process; status reported to wait(). No return. |
int wait(int *status) | Wait for a child to exit; exit status in *status; returns child PID. |
int kill(int pid) | Terminate process PID. Returns 0, or -1 for error. |
int getpid() | Return the current process’s PID. |
int sleep(int n) | Pause for n clock ticks. |
int exec(char *file, char *argv[]) | Load a file and execute it with arguments; only returns if error. |
char *sbrk(int n) | Grow process’s memory by n bytes. Returns start of new memory. |
int open(char *file, int flags) | Open a file; flags indicate read/write; returns an fd (file descriptor). |
int write(int fd, char *buf, int n) | Write n bytes from buf to file descriptor fd; returns n. |
int read(int fd, char *buf, int n) | Read n bytes into buf; returns number read; or 0 if end of file. |
int close(int fd) | Release open file fd. |
int dup(int fd) | Return a new file descriptor referring to the same file as fd. |
int pipe(int p[]) | Create a pipe, put read/write file descriptors in p[0] and p[1]. |
int chdir(char *dir) | Change the current directory. |
int mkdir(char *dir) | Create a new directory. |
int mknod(char *file, int, int) | Create a device file. |
int fstat(int fd, struct stat *st) | Place info about an open file into *st. |
int stat(char *file, struct stat *st) | Place info about a named file into *st. |
int link(char *file1, char *file2) | Create another name (file2) for the file file1. |
int unlink(char *file) | Remove a file. |
# fork
fork()
系统调用通过复制当前进程创建新进程。子进程从父进程的初始状态开始运行,在父进程 fork()
处停止运行并返回 0
. 父进程 fork()
返回子进程的 PID. 下面是一个样例:
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
int | |
main(int argc, char *argv[]) | |
{ | |
printf("hello world (pid:%d)\n", (int) getpid()); | |
int rc = fork(); | |
if (rc < 0) { // fork failed; exit | |
fprintf(stderr, "fork failed\n"); | |
exit(1); | |
} else if (rc == 0) { // child (new process) | |
printf("hello, I am child (pid:%d)\n", (int) getpid()); | |
} else { // parent goes down this path (main) | |
printf("hello, I am parent of %d (pid:%d)\n", | |
rc, (int) getpid()); | |
} | |
return 0; | |
} |
该程序的输出可能为
hello world (pid:29146)
hello, I am parent of 29147 (pid:29146)
hello, I am child (pid:29147)
也可能为
hello world (pid:29146)
hello, I am child (pid:29147)
hello, I am parent of 29147 (pid:29146)
存在多种可能输出的原因是,父进程和子进程是并发执行的。
# exec
exec(char* file, char *argv[])
的作用是执行一个文件中的程序,其传入参数 file
为文件名, argv
为新程序的指令。当 exec
成功被调用时,它将没有返回。仅当其运行出现错误时返回。
# pipe
参考一只小香羊: linux 管道 pipe 使用。
pipe()