Reputation: 41
Hi i'm just trying to use posix_spawn on OSX , this should work find (as for *nix) anyway after posix_spawn syscall the process will receive SIGTRAP i really cannot uderstand why.
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
while(1){
char *newargv[] = { "/usr/bin/id", 0 };
char *newenviron[] = {0};
posix_spawnattr_t * a;
posix_spawn_file_actions_t * fa;
fa = malloc(0x80);
a = malloc(336);
//printf("size: %d\n", sizeof(posix_spawnattr_t));
posix_spawnattr_init(a);
posix_spawnattr_setflags(a, 0x40);
posix_spawn_file_actions_init(fa);
pid_t pid;
int status = 0;
posix_spawn(&pid, "/usr/bin/id", fa, a, newargv, newenviron);
waitpid(pid, &status, 0);
printf("pid: %d\n", pid);
}
//printf("pid: %d\n", pid);
return 0;
}
It should run forever but the output from id will be printed just one time.
Thanks for your support!
Upvotes: 1
Views: 1030
Reputation: 207670
Not sure what you are actually trying to do, because you have hard-coded constants and sizes in that may not be relevant on macOS.
The main problem is that your 0x40
flag means that /usr/bin/id
is exec'ed - just once and replaces the current process so it doesn't go around the loop again!
Other problems should be visible from the version below:
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *newargv[] = { "/usr/bin/id", 0 };
char *newenviron[] = {0};
posix_spawnattr_t a;
posix_spawnattr_init(&a);
// posix_spawnattr_setflags(&a, 0x40); exec & replace the current process !!!
pid_t pid;
int status = 0;
while(1){
posix_spawn(&pid, "/usr/bin/id", NULL, &a, newargv, newenviron);
waitpid(pid, &status, 0);
printf("pid: %d\n", pid);
}
return 0;
}
The difference between what you have:
posix_spawnattr_t * a;
a = malloc(336);
and what I have:
posix_spawnattr_t a;
is that firstly, mine is the correct size no matter how the structure is defined on any particular OS, whereas yours is a hard-coded number that may or may not be correct for any particular OS, and secondly, your method leaks 336 bytes of memory every time through the loop which, given that there is no delay or anything else in the loop, might mean more of a gushing tap/faucet than a minor leak ;-)
Upvotes: 1