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; }