Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux CreateProcess?

I developing on the Linux platform.

I want to create a new proccess in my library without replacing the current executing image.

Because I am developing a library, I don't have a main function.

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

Is it possible in 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, it is not good. I want to continue the current process.

  • exec() family replace the current executing image, it is not good.

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

like image 327
Amir Saniyan Avatar asked May 04 '11 12:05

Amir Saniyan


2 Answers

The fork/exec combination was already mentioned, but there is also the posix_spawn family of functions that can be used as a replacement for fork + exec and is a more direct equivalent to CreateProcess. Here is an example for both possibilities:

#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));
  }
}
like image 134
Philipp Avatar answered Sep 19 '22 19:09

Philipp


You wrote:

I want to create a new proccess in my library without replacing the current executing image. system() blocks the current process, it is not good. I want to continue current process.

Just add an ampersand after the command call. Example: system("/bin/my_prog_name &");

Your process will not be blocked!

like image 32
Ivan Avatar answered Sep 23 '22 19:09

Ivan