In linux, how does one compile a function similar to CreateProcess? -- Linux general technology-Linux programming and kernel information. The following is a detailed description. My current requirement is to compile a UDF similar to the Windows CreateProcess function in linux. the functional requirements include the following:
1. return immediately after the program is executed. you do not need to return the execution result of the created program. Instead, you need to return whether the subroutine fork is successful.
2. the sub-process automatically exits after the execution is complete. no zombie process is required to wait for the parent process to be recycled.
3. the child process does not inherit any resources of the parent process (file descriptor ...)
My current implementation is fork () + exec () + waitpid (pid, & status, WNOHANG | WUNTRACED) <--------- Don't wait to exit directly
The following problems are encountered:
1. the parent process cannot obtain whether the sub-process exec is successfully executed.
2. sometimes there will be zombie processes
3. the child process inherits the file descriptor opened by the parent process (ask how to use clone to solve this problem)
How can I modify it to meet my requirements?
Or there is a similar implementation in that library. I can study it.
Code:
CODE: // This function executes the program specified by exepath // Failed and failed to return Int execute_new (const char * exepath, const char * arg, unsigned int & retpid) { If (exepath = NULL) { Return 0; }
Int argcount = 0; Char * argv [1024] = {0 }; Char argsave [1024] = {0 }; Char * argline = argsave; Argv [0] = (char *) exepath; Argcount ++;
////////// Split and extract parameters as parameters of the execvp function If (arg! = NULL) { Strncpy (arg save, arg, 1024-1 ); Int is_find_space =-1; //-1, If (* argline! = '') { Argv [argcount] = (char *) argline; Argcount ++; } While (* argline! = '\ 0 ') { If (* argline = ''& * (argline + 1 )! = ''& * (Argline + 1 )! = '\ 0 ') { Argv [argcount] = (char *) (argline + 1 ); Argcount ++; } If (* argline = '') { * Argline = '\ 0 '; } Argline ++; } }
Pid_t pid; Int status; If (pid = fork () <0 ){ Status =-1; } Else if (pid = 0 ){ Execv (exepath, argv ); _ Exit (127); // The sub-process will not execute this statement if it is executed normally. } Else {
Retpid = pid;
Waitpid (pid, & status, WNOHANG | WUNTRACED );
} Return status; } |