2

How would I go about printing a process id before the process is actually executed? Is there a way I can get the previously executed process id and just increment?

i.e.

printf(<process id>); execvp(process->args[0], process->args); 
2
  • 1
    Why would you like to do that?? Commented Jun 10, 2012 at 6:29
  • 2
    @obounaim that's actually how you know the PID of the children so you know what to do with them - fork() returns the PID of child which is preserved by exec Commented Jun 10, 2012 at 6:30

2 Answers 2

8

exec family of syscalls preserve current PID, so just do:

if(fork() == 0) { printf("%d\n", getpid()); execvp(process->args[0], process->args); } 

New PIDs are allocated on fork(2), which returns 0 to child process and child process' PID to parent.

Sign up to request clarification or add additional context in comments.

1 Comment

So I guess this probably isn't what @Milk is after (presumably the PID of the forked process) -- something that not even the kernel knows until you run fork.
2

You'll need to fork() and then run one of the exec() functions. To get the data from the child process, you'll need some form of communication between child and parent processes since fork() will create a separate copy of the parent process. In this example, I use pipe() to send data from child process to the parent process.

int fd[2] = {0, 0}; char buf[256] = {0}; int childPid = -1; if(pipe(fd) != 0){ printf("pipe() error\n"); return EXIT_FAILURE; } pid_t pid = fork(); if(pid == 0) { // child process close(fd[0]); write(fd[1], getpid(), sizeof(int)); execvp(process->args[0], process->args); _exit(0) } else if(pid > 0){ // parent process close(fd[1]); read(fd[0], &childPid, sizeof(childPid)); } else { printf("fork() error\n"); return EXIT_FAILURE; } printf("parent pid: %d, child pid: %d\n", getpid(), childPid); return 0; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.