Bootstrap

进程API

fork()系统调用

创建一个子进程 子进程的rc返回是0 父进程返回的rc是子进程的id号

wait()系统调用

父进程等待子进程执行完再继续执行

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.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());
	sleep(1);
    } else {
        // parent goes down this path (original process)
        int wc = wait(NULL);//返回是子进程的id号
        printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
	       rc, wc, (int) getpid());
    }
    return 0;
}

exec()系统调用

内存空间都初始化,调用仿佛执行了一个新的程序一般

重定向

close(STDOUT_FILENO) 先是关闭屏幕输出(必须)
再打开一个文件 这样才能输出到指定文本中上 对应了Linux的重定向命令>

wc p3.c > newfile.txt
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>

int
main(int argc, char *argv[])
{
    int rc = fork();
    if (rc < 0) {
        // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) {
	// child: redirect standard output to a file
	close(STDOUT_FILENO); 
	open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);

	// now exec "wc"...
        char *myargs[3];
        myargs[0] = strdup("wc");   // program: "wc" (word count)
        myargs[1] = strdup("p4.c"); // argument: file to count
        myargs[2] = NULL;           // marks end of array
        execvp(myargs[0], myargs);  // runs word count
    } else {
        // parent goes down this path (original process)
        int wc = wait(NULL);
	assert(wc >= 0);
    }
    return 0;
}

作业8:管道通信
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

int main() {
	int pi[2];
	int p = pipe(pi);
	if(p < 0) {
		fprintf(stderr, "pipe failed");
		exit(1);
	}
	int i = 0;
	int rc[2];
	char buf[256];
	for(i=0;i<2;++i) {
		rc[i] = fork();
		if (rc[i] < 0) {
			fprintf(stderr, "fork failed");
			exit(1);
		} else if (rc[i] == 0) {
			switch(i) {
			case 0:
				dup2(pi[1], STDOUT_FILENO); //管道绑定
				puts("child input");
				break;
			case 1:
				dup2(pi[0], STDIN_FILENO);
				gets(buf);
				printf("child0 out (%s) in the child1\n", buf);
				return 2;
			}
			break;
		}
	}
	waitpid(rc[0], NULL, 0);
	waitpid(rc[1], NULL, 0);
	return 0;
}
;