linux下使用系統調用實現進程後臺運行

其實很簡單,就是把
if(fork()==0)
{
    execve(...);
}
else
{
wait(state);
}
結構中的else去掉就可以了
下面是一個示例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc,char** argv)
{
  int * status;
  int gc;
  char command[64]="./clu";
  char comarg[64]="";
  argv[1]=comarg;
  while(1)
    {
      if((gc=getchar())=='g')
 {
   if(fork()==0)
     {
       if(execve(command,argv,0)==-1)
  {
    printf("process error is %s/n",strerror(errno));
  }
       printf("process is ok/n");
     }
 }
      if(gc=='k')
 {
   printf("to be continue/n");
 }
      if(gc=='e')
 {
   return 1;
 }
    }
 }

功能是這樣的,啓動以後會從鍵盤接受字符,如果是g就運行預先指定好的程序(在這裏是一個叫clu的程序),如果是k就打印to be continue,如果是e就退出
下面是這個叫clu的程序的代碼
#include <stdio.h>
#include <time.h>

int main()
{
  long begin=0;
  long end=24000;
  long finish=0;
  long loop1,loop2;
  time_t flag;
  time_t nowtime1,nowtime2;
  if((flag=time(&nowtime1))==-1)exit(1);
  for(loop1=begin;loop1<end;loop1++)
    {
      for(loop2=begin;loop2<end;loop2++)
 {
   if((loop1%2)==0)
     {
       if((loop2%2)==0)
  {
    if(finish>65535)
      finish=0;
    finish+=((loop1/2+loop2/2)%2)%2;
  }
     }
 }
    }
  if((flag=time(&nowtime2))==-1)exit(1);
  printf("%ld/n",finish);
  printf("proccess time %ldsec/n",nowtime2-nowtime1);
}
這個程序本身沒有任何意義,只是純粹的延誤一下時間,輸出一下運行的時間,便於測試,在我的AMD2500+上,大概是5秒,你可以試試哦^_^

要測試這個程序,可以在程序運行時輸入g,但是這個計算不會馬上結束,在屏幕還沒有輸出的時候再輸入k,就會先輸出k的內容,後臺clu的結果出來後才輸出到屏幕,也就是clu在後臺運行了

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章