// Create child process && exec current program [ set lock ]
// Windows
#include
#include
#include
#include
#define MAX_LINE_LEN 80
bool checkRunning()
{
int res = access("d:\lock.dat", 0);
if (res == 0) {
printf("exit....\n");
return true;
}
FILE* fid;
fid = fopen("d:\lock.dat", "w+");
char a[] = "ddd";
fwrite(a, strlen(a), 1, fid);
fclose(fid);
return false;
}
int main(int argc, char* argv[])
{
//local variables
FILE* fid;
char cmdLine[MAX_LINE_LEN];
//CreateProcess parameters
LPSECURITY_ATTRIBUTES processA=NULL;//Default
LPSECURITY_ATTRIBUTES threadA=NULL;//Default
BOOL shareRights=TRUE;//Default
DWORD creationMask=CREATE_NEW_CONSOLE;//Window per process.
LPVOID enviroment=NULL;//Default
LPSTR curDir=NULL;//Default
STARTUPINFO startInfo;//Result
PROCESS_INFORMATION procInfo;//Result
if (checkRunning()) {
Sleep(1000 * 20 );
}
//1.Read the command line parameters
if(argc!=2)
{
fprintf(stderr,"Usage:lanch\n");
exit(0);
}
//2.Open a file that coutain a set of commands
fid=fopen(argv[1],"r");
if (fid == NULL) {
printf("function fopen() failed!!!\n");
return 1;
}
//3.For every command in the launch file
while(fgets(cmdLine,MAX_LINE_LEN -1 ,fid)!=NULL)
{
//Read a command from the file
if(cmdLine[strlen(cmdLine)-1]=='\n')
cmdLine[strlen(cmdLine)-1]='\0';//Remove NEWLINE
//Create a new process to execute the command
ZeroMemory(&startInfo,sizeof(startInfo));
startInfo.cb=sizeof(startInfo);
printf("%s\n", cmdLine);
if(!CreateProcess(
NULL,//File name of executable
cmdLine,//command line
processA,//Process inherited security
threadA, //Thread inherited security
shareRights,//Rights propagation
creationMask,//various creation flags
enviroment,//Enviroment variable
curDir, //Child's current directory
&startInfo,
&procInfo
)
)
{
fprintf(stderr,"CreatProcess failed on error %d\n",GetLastError());
ExitProcess(0);
}
}
Sleep(1000 * 40 );
//Terminate after all commands have finished.
return 0;
}
// fork() child process && exec other program
// Linux .
#include
#include
#include
using namespace std;
int main()
{
cout << "test process begin..." << endl;
string child_process = "./out_child";
cout << "begin to create child process: " << child_process << endl;
pid_t pd = fork();
if (pd == 0 ) {
cout << "########### child ################" << endl;
int res = execl(child_process.c_str(), (char*)NULL);
if (res < 0 ) {
cout << "function execl() failed!!!" << endl;
}
cout << "########### child ################" << endl;
}
else if (pd > 0) {
sleep(30);
}
else {
cout << "function fork() failed!!!" << endl;
}
cout << "test process end..." << endl;
return 0;
}
阅读(1889) | 评论(0) | 转发(0) |