嵌入式 一个进程获取另一个指定名称进程的PID

1、我们可以直接使用管道获取

ps u | awk '/\.\/sigrecevice$/{print $2}'

注意:转义字符打印的时候需要两次转义:打印“\t” 为“\\t”

2、如果想获取之后保存在变量中,则实现代码如下:

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #define __DEBUG__

#ifdef __DEBUG__ #define msg_print(...) printf(__VA_ARGS__) #else #define msg_print(...) #endif

#define MAX_VALUE_LEN 32

int joseph_get_name_pid(const char *key, char *value);

int joseph_get_name_pid(const char *key, char *value) {     FILE *stream = NULL;     char cmd[64] = {0};     char  buf[8] = {0};     if(NULL == key || 0 == strlen(key)){  msg_print("invalid parameter!\n");  return -1;     }     strcpy(buf,"\\.\\/");     printf("%s %d The buf is %s\n",__FUNCTION__,__LINE__,buf);     //sprintf(cmd, "ps u | awk '/%s$/{print $2}' | sed -n '1p'",key);     sprintf(cmd, "ps u | awk '/%s%s$/{print $2}'",buf,key);     msg_print("cmd = %s\n",cmd);

    stream = popen(cmd,"r");

    if(fread(value, sizeof(char), MAX_VALUE_LEN, stream) <= 0){  pclose(stream);  return -1;     }     strcpy(value + strlen(value) - 1, "\0");     msg_print("%s = %s\n", key, value);

    pclose(stream);     return 0; }

int main(int argc,char *argv[]) {     char value[32] = {0};     int name_pid = 0;     if(argc != 2)     {  printf("%s %d The param is two !\n",__FUNCTION__,__LINE__);  return -1;     }     joseph_get_name_pid(argv[1] ,value);     if(strlen(value) == 0)     {  printf("%s %d The %s is not running !\n",__FUNCTION__,__LINE__,argv[1]);  return -1;     }     name_pid = atoi(value);     printf("%s %d The pid is %s(char) ,the pid length is %d !\n",__FUNCTION__,__LINE__,value,strlen(value));     printf("%s %d The pid is %d(int) !\n",__FUNCTION__,__LINE__,name_pid);     return 0; }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值