|

Getting Process Own Pid in C and C++

How to get the running process’ pid in C / C++?

In C and C++, you can call the getpid() library function which is a function from the POSIX library.

#include <sys/types.h>
#include <unistd.h>

pid_t getpid(void);

getppid() returns the process ID of the calling process.

An example C program to get self process ID getpid.c:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
  pid_t pid = getpid();

  printf("pid: %lu\n", pid);
}

Build and run it:

$ gcc getpid.c -o s && ./s
pid: 7108

Similar Posts

  • |

    Synchronizing home directories

    Any good tools to synchronize home directories on Linux boxes? Many have several PC/laptops and consequently many home directories. There is home directory synchronizing problem. unison is a good tool to do this: http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#rshmeth http://www.watzmann.net/blog/2009/02/my-homedirs-in-unison.html http://www.cis.upenn.edu/~bcpierce/papers/index.shtml#File%20Synchronization Useful script: $ unison -batch -ui text ./ /mnt/homebak/zma/ In text user interface, synchronizing two directories in batch mode…

  • MFC中屏蔽ESC和回车关闭对话框

    解决方法是在CDialog::PreTranslateMessage() 的重载函数中将ESC和回车按键的消息处理掉. 直接上代码: BOOL CResultCollectorDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message == WM_KEYDOWN) { switch(pMsg->wParam) { case VK_RETURN: //回车 return TRUE; case VK_ESCAPE: //ESC return TRUE; } } return CDialog::PreTranslateMessage(pMsg); } Read more: MFC程序使用系统风格界面 Send Messages to Other Windows Using Win32 API 禁止对话框关闭按钮和Alt+F4 使用MFC在一对话框中嵌入另一对话框 一个非常优秀的MFC Grid控件 Win32 Programming: Operation on Files Java Calling Native Functions in .DLL on…

2 Comments

  1. Please update the reuslt section with actual result.

    $ gcc getpid.c -o s && ./s
    ppid: 7108

    But printf is
    printf(“pid: %lun”, pid);

    How come it prints “ppid” for print statement of “pid”.

  2. Hello, thanks for the idea but getpid() returns an int so the format in printf is abnormal : %lun should be just %d (and the n in lun is probably a typo)

    the error :
    error: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘pid_t’ {aka ‘int’}

    x86_64 architecture, 64 bits

Leave a Reply

Your email address will not be published. Required fields are marked *