02
2014
05

UC编程6-目录操作和创建子进程fork()函数1

//myuc.h

#include<stdio.h>//io流
#include<stdlib.h>//标准库
#include<unistd.h>//uc标准头文件
#include<fcntl.h>//文件控制
#include<string.h>//c字符串
#include<sys/types.h>
#include<sys/mman.h>//内存映射
#include<sys/stat.h>//文件状态信息
#include<sys/wait.h>//进程等等
#include<dirent.h>//目录操作
#include<signal.h>//信号
#include<sys/time.h>//时间,计时器
#include<sys/ipc.h>//ipc进程间通信
#include<sys/shm.h>//共享内存段
#include<sys/msg.h>//消息队列


//operatordir6.c

#include "myuc.h"
void test1()
{
DIR* dir=opendir("./");
if(dir==NULL) perror("opendir"),exit(-1);
struct dirent * ent;
while(ent=readdir(dir))//
{
//类型4:目录,8:文件
printf("type:%d,name:%s\n",ent->d_type,ent->d_name);
}
}
//递归显示目录
void print(const char* name){
printf("dir:[%s]\n",name);
DIR* dir=opendir(name);
if(dir==NULL) {perror("opendir");return;}
struct dirent * ent;
while(ent=readdir(dir))//
{
//类型4:目录,8:文件
if(ent->d_type!=4)
{
printf("type:%d,name:%s\n",ent->d_type,ent->d_name);
}
else if(ent->d_type==4&& strcmp(ent->d_name,".")
&&strcmp(ent->d_name,".."))
{
//printf("dir:[%s]\n",ent->d_name);
char pd[256]={};
strcpy(pd,name);
if(name[strlen(name)-1]!='/') strcat(pd,"/");
//拼接子目录相对地址
strcat(pd,ent->d_name);
strcat(pd,"/");
//printf("pd:%s\n",pd);
print(pd);
}
}
}
int main()
{
//test1();
print("../c");
return 0;
}


//fork6.c

#include "myuc.h"
void test1()
{
pid_t pid=fork();//调用一次返回两次,
//如果当前进程是父进程,则返回子进程id,如果当前是子进程 ,则返回0
if(pid==0) {//子进程
   sleep(2);
printf("1子进程id:%d\n",getpid());
printf("1父进程id:%d\n",getppid());
}
else{
printf("2父进程id:%d\n",getpid());
printf("2子进程id:%d\n",pid);
}
sleep(1);//如果父进程运行完毕退出了,子进程的父进程会变化。
//return 0;
}
int i=10;
void test2()
{
int i2=10;
int *pi=malloc(4);
*pi=10;//fork之前,复制的变量,地址一样的
pid_t pid=fork();
int i4=10;//fork之后,不是复制,地址可能不一样
if(pid==0){
i=20;i2=20;*pi=20;i4=20;
printf("1:i=%d,i2=%d,*pi=%d,i4=%d\n",
i,i2,*pi,i4);
printf("1:%p,%p,%p,%p\n",&i,&i2,pi,&i4);
exit(0);//退出子进程
}
printf("2:i=%d,i2=%d,*pi=%d,i4=%d\n",
i,i2,*pi,i4);
printf("2:%p,%p,%p,%p\n",&i,&i2,pi,&i4);
sleep(2);
}
void test3()
{
pid_t pid=fork();
int fd=open("a.txt",O_RDWR|O_CREAT,0700);
if(fd==-1) perror("open"),exit(-1);
//pid_t pid=fork();
if(pid==0){
write(fd,"abc",3);
close(fd);
exit(0);
}
write(fd,"def",3);
close(fd);
sleep(1);
}
int main()
{
test1();
//test2();
//test3();
return 0;
}




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。