Linux编程基础 文件操作、进程管理


一.函数

1.stat函数用于获取文件的属性

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

2.access函数用于测试文件是否拥有某种权限

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

3.chmod函数用于修改文件的访问权限

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

4.truncate函数用于修改文件大小,常用于扩展文件,其功能与lseek函数类似

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

二、使用步骤

fork()函数创建

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

返回值:

成功:返回两个值,子进程创建成功后,原程序会被复制,就有了两个fork函数。父进程的fork函数会返回子进程的pid,子进程的fork函数会返回0.
不成功:若子进程创建失败,原程序不会复制,父进程的fork函数返回
案例:

#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......");
    return 0;
}//of main

多次执行test_fork会发现,child process后输出的ppid不等于parent process的pid,而等于1,这是由于父进程先于子进程终止,子进程变成“孤儿进程”,后面由init进程来接收

多个子进程的创建

int i;
for(i = 0;i < 3 ; i++){
   pid=fork();
}
test_fork2.c
#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

如果只希望父进程可以创建新进程,则在for循环中添加一个判断:若当前进程不是父进程,则跳出循环

#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

父进程的阻塞时间设置的要比最后一个子进程创建的阻塞时间还要长,只能长不能短

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值