Both getppid() and getpid() are inbuilt functions defined in unistd.h library.
- getppid() : returns the process ID of the parent of the calling process. If the calling process was created by the fork() function and the parent process still exists at the time of the getppid function call, this function returns the process ID of the parent process. Otherwise, this function returns a value of 1 which is the process id for init process.
Syntax:
pid_t getppid(void);
Return type: getppid() returns the process ID of the parent of the current process. It never throws any error therefore is always successful. Output(Will be different on different systems):CPP // C++ Code to demonstrate getppid() #include <iostream> #include <unistd.h> using namespace std; // Driver Code int main() { int pid; pid = fork(); if (pid == 0) { cout << "\nParent Process id : " << getpid() << endl; cout << "\nChild Process with parent id : " << getppid() << endl; } return 0; }
Parent Process id of current process : 3849 Child Process with parent id : 3851
NOTE: At some instance of time, it is not necessary that child process will execute first or parent process will be first allotted CPU, any process may get CPU assigned, at some quantum time. Moreover process id may differ during different executions. - getpid() : returns the process ID of the calling process. This is often used by routines that generate unique temporary filenames.
Syntax:
pid_t getpid(void);
Return type: getpid() returns the process ID of the current process. It never throws any error therefore is always successful. Output (Will be different on different systems):CPP // C++ Code to demonstrate getpid() #include <iostream> #include <unistd.h> using namespace std; // Driver Code int main() { int pid = fork(); if (pid == 0) cout << "\nCurrent process id of Process : " << getpid() << endl; return 0; }
Current process id of Process : 4195