fork

来源:互联网 发布:西安财经行知特点 编辑:程序博客网 时间:2024/06/05 14:20

#include <stdio.h>


/*Question 1*/
/*a: the array need the length for another argument, the wrong line number is 5*/
/*b: the wright code fill function*/
void fill(int array[], int length)
{
 int i;
 for (i=0; i<length; i++)
  array[i] = i;
}


/*Question 2*/
/*a: the wrong line number is: 15, because the struct need Byte aligned by default*/
/*b: thw wright code :*/

memset(array, -1, sizeof(struct T)* SIZE);


/*Question 3*/
/*a: the actual output:  nothing ouput*/
/*
b: int execl(const char * path, const char * arg, ...);
the argument is from argv[0], argv[1]....
*/
#include <stdio.>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
 if (fork() == 0)
 {
  execl("./alice", "./alice", NULL);
  return 0;
 }
 wait(NULL);

 if (fork()==0)
 {
  execl("./bob", "./bob", NULL);
  return 0;
 }
 wait(NULL);
 return 0;
}

/*Question 4*/
/*the right code of daemon*/

void init_daemon(void)
{
 int pid;
 int i;
 if(pid=fork())
  exit(0);        //是父进程,结束父进程
 else if(pid< 0)
  exit(1);        //fork失败,退出
 //是第一子进程,后台继续执行
 setsid();           //第一子进程成为新的会话组长和进程组长
 //并与控制终端分离
 if(pid=fork())
  exit(0);        //是第一子进程,结束第一子进程
 else if(pid< 0)
  exit(1);        //fork失败,退出
 //是第二子进程,继续
 //第二子进程不再是会话组长
 for(i=0;i< 1024;++i)  //关闭打开的文件描述符
  close(i);

 chdir("/tmp");      //改变工作目录到/tmp
 umask(0);           //重设文件创建掩模
 return;
}


 

0 0