I need to write wrapper functions for fork and signal functions. These functions will handle errors by fork() and signal() and exit, if an error occurs.

The problem is I am not sure exactly what to check for on either function.

Here is some sample code for both of them. Fork does not work correctly (I'm guessing I may need to use fprintf instead of perror) and I am not sure if I am returning the right thing for signal.

Any help greatly appreciated.

pid_t Fork(void) {

pid_t p;


    if ((p=fork())<0) {
                    perror ("fork error");
                    exit(12);
                    }

    return p;

}





void (*Signal (int sig, void (*disp) (int))) (int) {

    if ((signal(sig, disp))==SIG_ERR) {
                    perror ("signal error");
                    exit(13);
                    }

return (*disp);
}

Recommended Answers

All 6 Replies

Member Avatar for iamthwee

maybe in need to be p==fork?

No, the call to fork() is correct --I see nothing wrong with it.
You are aware that this is a *nix system function and it will not work on Windows, right?

I'm not sure what you are trying to do with the signal. Are you trying to make a pointer to a function or a function itself? Choose one. (And either way, watch your syntax!)

Hope this helps.

Yep, this will run on a Solaris machine.

Basically, I need the wrapper functions to do the regular job of the functions, EXCEPT for when an error occurs. In that case I need to print an error message and quit as seen above. This is done so that in your main program, you can call

Fork();

instead of :
(pseudo-code)

if (Fork()!=success) exit(1);......

My problem is, I am not sure what the two functions above really return. I've looked at man pages and I am not very sure how to write this in the code.

Yes, I understand that. What are you trying to do with that signal function? Are you trying to make something of a signal handler that calls another signal handler and crashes the program if the other handler fails? (If so, that's smart idea, but still not a very good thing to do.)

Ah, your edit.

fork() returns one of three things:
- a negative number on error (which you know)
- zero if you are the newly created child process
- the PID of the child process created if you are the parent process

A signal handler isn't supposed to return anything. Here is a good reference I just googled.

Hope this helps.

Yes. Here is the signal handler:

void sig_chld(int signo)
{
    pid_t pid;
    Signal(SIGCHLD, sig_chld);

    pid = Wait(0);
    printf("child %d terminated\n", (int)pid);
}

and the call to it from within the main program:

Signal(SIGCHLD, sig_chld);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.