Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I fork processes and exec internal functions?

Tags:

c

fork

exec

I've really searched for this and all I can find is that you can execvp() shell commands.

I'm wondering if I can fork processes and then have them run a function that's internal to the program? (As in, a function I've written myself within the code)

like image 782
Anthony Capps Avatar asked Feb 24 '26 08:02

Anthony Capps


1 Answers

Of course you can have the child execute one function and the parent execute a different (or even the same) function in the same executable.

pid_t pid = fork();
if (pid < 0)
    err_syserr("failed to fork: ");
else if (pid == 0)
    be_childish();
else
    be_parental();

You can add arguments to be_childish() and be_parental() as needed. Before the code executes fork(), you can create pipes or sockets to communicate between them — or semaphores, and shared memory, or whatever IPC you want.

like image 153
Jonathan Leffler Avatar answered Feb 27 '26 01:02

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!