Exécuter une commande shell dans un programme ac

Je veux lancer une commande shell dans mon programme c. Mais le fait est que je ne veux pas que mon programme attende que la commande soit exécutée. Pas besoin de lire la sortie de la commande shell (elle ne renvoie de toute façon aucune donnée) Donc, est-ce possible?

fork() et system() sont ce dont vous avez besoin

Bien sûr, juste fork et exec : utilisez fork pour créer un nouveau processus et, dans le processus fils, utilisez exec pour démarrer le shell avec votre commande. execv prend les arguments que vous donneriez normalement au shell.

Votre code pourrait ressembler à ceci:

 pid_t child_pid = fork(); if (child_pid == 0) { // in child /* set up arguments */ // launch here execv("/bin/sh", args); // if you ever get here, there's been an error - handle it } else if (child_pid < 0) { // handle error } 

le processus fils enverra un signal SIGCHLD lorsqu'il mourra. Ce code cité dans la norme POSIX (SUSv4) gérera cela:

 static void handle_sigchld(int signum, siginfo_t *sinfo, void *unused) { int status; /* * Obtain status information for the child which * caused the SIGCHLD signal and write its exit code * to stdout. */ if (sinfo->si_code != CLD_EXITED) { static char msg[] = "wrong si_code\n"; write(2, msg, sizeof msg - 1); } else if (waitpid(sinfo->si_pid, &status, 0) == -1) { static char msg[] = "waitpid() failed\n"; write(2, msg, sizeof msg - 1); } else if (!WIFEXITED(status)) { static char msg[] = "WIFEXITED was false\n"; write(2, msg, sizeof msg - 1); } else { int code = WEXITSTATUS(status); char buf[2]; buf[0] = '0' + code; buf[1] = '\n'; write(1, buf, 2); } } 

Essayez le code comme ceci:

 #include  #include  int main(int argc, char ** argv) { if (!fork()) { execv("ls", {"myDir"}); /* Your command with arguments instead of ls. */ } } 

Qu’en est-il simplement de l’amplification de la commande avec le system ("command &") ?