系统级程序设计 第二节课

阅读 55

2022-05-06

一、进程管理

1.1 fork() 创建进程

#include <unistd.h>
pid_t fork(void);

1.2 创建子进程

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
	pid_t tempPid;
	tempPid = fork();
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
	}else{//child
		printf("child process, pid = %d, ppid = %d\n", getpid(), getppid());
	}//of if
	printf("......finish......\n");
	return 0;
}//of main

在语句fork()之前,只有一个进程在执行这段代码,但在这条语句之后,就变成两个进程在执行了,这两个进程的几乎完全相同,将要执行的下一条语句都是if()....

1.3 循环创建多个子进程

int i;
for(i = 0; i < 2; i ++){
	tempPid = fork();
}//of for i

for循环:每次调用fork函数,系统会复制原程序

每一次循环,进程的总数是当前进程数量的两倍,2次循环则为2^2=4个进程。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		}//of if
	}//of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
	}else{//child
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	}//of if
	printf("......finish......");
	return 0;
}//of main

 1.4 进程的执行顺序:利用sleep函数,暂缓进程执行

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
	pid_t tempPid;
	int i;
	for(i = 0; i < 2; i ++){
		if((tempPid = fork()) == 0){
			break;
		}//of if
	}//of for i
	if(tempPid == -1){
		perror("fork error");
	}else if(tempPid > 0){//parent
		sleep(2);
		printf("parent process, pid = %d, ppid = %d\n", getpid(), getppid());
	}else{//child
	 	sleep(i);
		printf("I am child process = %d, pid = %d, ppid = %d\n", i + 1, getpid(), getppid());
	}//of if
	printf("......finish......");
	return 0;
}//of main

二、文件操作函数

2.1 stat函数

#include <sys/stat.h> 
int stat(const char *path, struct stat *buf);

path:文件路径;

buf:接收获取到的文件属性;文件属性存储在inode中,函数从inode结构体中获取文件信息。

2.2 access函数

#include <unistd.h> 
int access(const char *pathname, int mode);

pathname:文件名;

mode:取值有4个:R_OK, W_OK, X_OK, F_OK;前面3个是测试文件是否有读、写、执行权限,最后一个测试文件是否存在。

2.3 chmod函数

#include <sys/stat.h> 
int chmod(const char *path, mode_t mode);

path:路径名;

mode:传递修改后的权限。

2.4 truncate函数

#include <sys/stat.h> 
int truncate(const char *path, off_t length);

path:路径名;

length:设置文件大小。

精彩评论(0)

0 0 举报