Linux CreateProcess?

I am developing a Linux platform.

I want to create a new process in my library without replacing the current executable image.

Since I am developing the library, I do not have the main function.

And I want to continue the new process after closing the invoker application (just like CreateProcess Windows API).

Is this possible on Linux or not?

something like this function:

void Linux_CreateProcess(const char* app_name)
{
  // Executing app_name.

  // ???????? what is the code ??????

  // app_name is running and never close if current application close.
  return;
}

Note:

  • system () blocks the current process, this is not good. I want to continue the current process.

  • exec () will replace the current executable image, this is not good.

  • popen () closes the new process if the current process is closed.

+5
source share
8 answers

fork(), exec() .

fork() ( vfork()), , . , fork , . exec() .

: http://davmac.wordpress.com/2008/11/25/forkexec-is-forked-up/

+11

fork/exec , posix_spawn , fork + exec CreateProcess. :

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>

extern char **environ;

void test_fork_exec(void);
void test_posix_spawn(void);

int main(void) {
  test_fork_exec();
  test_posix_spawn();
  return EXIT_SUCCESS;
}

void test_fork_exec(void) {
  pid_t pid;
  int status;
  puts("Testing fork/exec");
  fflush(NULL);
  pid = fork();
  switch (pid) {
  case -1:
    perror("fork");
    break;
  case 0:
    execl("/bin/ls", "ls", (char *) 0);
    perror("exec");
    break;
  default:
    printf("Child id: %i\n", pid);
    fflush(NULL);
    if (waitpid(pid, &status, 0) != -1) {
      printf("Child exited with status %i\n", status);
    } else {
      perror("waitpid");
    }
    break;
  }
}

void test_posix_spawn(void) {
  pid_t pid;
  char *argv[] = {"ls", (char *) 0};
  int status;
  puts("Testing posix_spawn");
  fflush(NULL);
  status = posix_spawn(&pid, "/bin/ls", NULL, NULL, argv, environ);
  if (status == 0) {
    printf("Child id: %i\n", pid);
    fflush(NULL);
    if (waitpid(pid, &status, 0) != -1) {
      printf("Child exited with status %i\n", status);
    } else {
      perror("waitpid");
    }
  } else {
    printf("posix_spawn: %s\n", strerror(status));
  }
}
+32

- fork() , exec() , . .

+3

:

.   system() , . .

. : system("/bin/my_prog_name &");

!

+3

fork(), execvp().

fork() . . Child 0, , .

execvp() . . , ; . execvp , fork.

+2

, fork() exec..() - . , :

switch( fork() )
{
    case -1 : // Error
            // Handle the error
            break;

    case 0 :
            // Call one of the exec -- personally I prefer execlp
            execlp("path/to/binary","binary name", arg1, arg2, .., NULL);

            exit(42); // May never be returned
            break;

    default :

            // Do what you want
            break;  
}
+2

, posix_spawn , . fork/exec, , , .

+2

, fork - , .

0

All Articles