1.操作文件的系统调用 : open,read,write,close
fopen()->会调用 open
int fd=open(“file.txt”,O_WRONLY|O_CREAT,0600); 6代表读写
只写 ,如果没有就创建
write(fd,"hello",5);
close(fd);
int fd=open(“file.txt”,O_RDONLY);
只读
char buff[128]={0};
int n=read(fd,buff,127);
printf("buff=%s,n=%d\n",buff,n);
close(fdw);
int fdr=open("6.jpg",O_RDONLY);
int fdw=open("7.jpg",O_WRONLY|O_CREAT,0600);
if(fdr==-1||fdw==-1)
{
exit(0);
}
char buff[1024]={0};
int num=0;
while((num=read(fdr,buff,1024))>0)
{
write(fdw,buff,num);
}
close(fdr);
close(fdw);
2.进程替换
1> exec 系列替换过程:pcb 使用以前的只修改,进程实体更换。
#include <unistd.h>
/*
*path:新替换的程序的路径名称
*arg :传给新程序主函数的第一个参数,一般为程序的名字
*arg 后面是剩余参数列表,参数个数可变,必须以空指针作为最后一个参数
*/
int execlp(const char* file, const char * arg,...);
int execle(const char* path, const char * arg,...,char* const envp[]);
int execv(const char * path, char* const argv[]);
int execvp(const char * file, char* const argv[]);
int execve(const char * path, char* const argv[],char* const envp[]);
2>(1) 以 ps 替换当前程序为例,介绍 exec 系统函数使用,注意该系列方法功能都一样,没有区别,只是参数不同:
excel使用代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
int main()
{
printf("main pid=%d\n",getpid());
//execl 执行成功不返回,直接从新程序的主函数开始执行,只有失败才返回错误码
execl("/bin/ps","ps","-f"(char*)0);
perror("execl error");
exit(0);
}
execve使用代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
int main()
{
//存放传给新程序主函数的参数
char* myargv[] = {"ps","-f",(char*)0};
//存放传给新程序主函数的环境变量
char* myenvp[] = {"MYSTR=hello","VAL=100",(char*)0};
printf("main pid=%d\n",getpid());
//execl 执行成功不返回,失败返回错误码
execve("/bin/ps",myargv,myenvp);
perror("execve error");
exit(0);
}
fork和exec联合使用创建一个全新的进程
当前主程序复制产生一个子进程,子进程用新程序“b”替换自身。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char* argv[],char* envp[])
{
printf("main pid=%d\n",getpid());
pid_t pid = fork();
assert( pid != -1 );
if ( pid == 0 )
{
char * myargv[] = {"b","hello","abc","123",(char*)0};
//char * myenvp[] = {"MYSTR=hello","VAL=100",(char*)0};
execve("./b",myargv,envp);
perror("execl error");
exit(0);
}
wait(NULL);
printf("main over\n");
exit(0);
}
新替换的b程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
int main(int argc, char* argv[],char* envp[])
{
printf("b pid=%d\n",getpid());
int i = 0;
printf("argc=%d\n",argc);
for( ; i < argc; i++ )
{
printf("argv[%d]=%s\n",i,argv[i]);
}
for( i = 0; envp[i] != NULL; i++ )
{
printf("envp[%d]=%s\n",i,envp[i]);
}
exit(0);
}