首页 > 代码库 > linux-系统调用

linux-系统调用

<style>p { margin-bottom: 0.1in; line-height: 120% }</style>

● Fork()

创建子进程。

创建单个子进程:

pid_t pid;

pid = fork();

if(pid == 0)

{

  printf("I am child, pid=%d. Father pid=%d\n", getpid(), getppid());

}

else if(pid > 0)

{

  printf("I am father, pid=%d. Child pid=%d\n", getpid(), pid);

}

else

{

  printf("failed..\n");

}

pid=0,为子进程;pid>0,为父进程;pid<0为失败。

getpid()返回当前进程pidgetppid()返回父进程pid


循环创建多个进程:

int i;

int pnum = 16;

pid_t pid;

printf("%d\n", getpid());

for (i = 0; i < pnum; i++)

{

  pid = fork();

  if (pid == 0 || pid == -1) break; //如果是子进程,则直接跳出,只允许父进程创建子进程,否则会循环创建。

}


if (pid == -1){

} //failed


//每个子进程都会执行的代码

else if (pid == 0)

{ }

//parent process

else

{}

用这个方法:http://blog.csdn.net/lanmanck/article/details/17892531

可以实现子进程向父进程返回值,但是exit()只能返回小于256的值。

● 直接IO

实现直接IO的方法:

1. fsync(fd)

2. 在用open打开文件的时候,用O_DIRECT标志

fd = open("/mnt/f2fs/test.txt", O_RDWR | O_CREAT | O_DIRECT, 0777))

3. 在用open打开文件的时候,用O_SYNC标志

 

参考:

http://blog.csdn.net/cosa1231116/article/details/6216331

linux-系统调用