其實很簡單,就是把
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在后臺運行了