【问题标题】:I'm creating a kill process using PID我正在使用 PID 创建一个终止进程
【发布时间】:2017-03-27 17:53:08
【问题描述】:

但是问题是我在通过方法发送到之前打印的PID和我在方法中接收到它之后打印的PID完全不同。我无法弄清楚。

void killbyPIDprocess(struct process** ptr,char* p)
 {
    int i=0;
    printf("hi");

 while(ptr[i]!=NULL)
{
    printf("Inside while loop");
    printf("%d\n",ptr[i]->pid);
    printf("%d\n",*p);
    if(strcmp(ptr[i]->pid,p)==0)
    {
        printf("Kill process of PID %d\n",p);

    }
    else
    {
        i++;
    }

}
}

在循环方法中,我的条件是

void loop(char *input)
 {
bool flag=true;
char **tokens;
  struct process **ptr=(struct process*) malloc (BUFFERSIZE);//Is the array that contains pointers to all the processes created.
int ci=0;int i=0;

while(flag==true)
{
    input=getInp(input);
    tokens=tokenize(input);
   if(strcasecmp(*tokens,"kill")==0)
    {
        strtok(tokens[1],"\n");
        char* pid=(char*)malloc (BUFFERSIZE);
        pid=tokens[1];
        printf("%s",pid);
        killbyPIDprocess(ptr, pid);

    }
    }

输入法只接受用户的输入。 tokenize 方法,使用 strtok 方法对输入进行标记。如果我输入 kill (PID),它将转到方法 killbyPIDprocess(ptr,pid),其中 ptr 是包含结构进程的所有指针的双指针。我在创建一个时存储进程信息。我在循环方法中打印的 pid 与我给它的输入相同,即我想要杀死我的进程的一个 pid,但是当我通过 killbyPIDprocess 方法传递这个 pid 时,它显示了一些其他值。我还没有开始实际处理终止代码,因为它一直给我错误。我使用打印语句来跟踪我的代码有多少工作。我对 C 语言比较陌生,而且是自学的,所以请指出错误。

【问题讨论】:

  • 我在 killbyPIDprocess() 中使用 *p 还是 p 都没关系。 p 显示垃圾值

标签: c process kill-process createprocess


【解决方案1】:

printf("%d\n",*p); 将为缓冲区中的第一个字符打印一个数字代码,因此您必须使用 %s 格式说明符 - printf("%s\n", p); 才能获得相同的结果。

此代码if(strcmp(ptr[i]->pid,p)==0) 也不正确。 process::pid 成员有一个 pid_t 类型,它是一个有符号整数。在字符串比较例程中使用它是一种未定义的行为(不确定它是否会编译)。要比较 PID,您必须将字符串数据转换为整数,例如使用 atoi 函数。然后您可以直接将它们与== 运算符进行比较。

【讨论】:

  • 谢谢。那么如何将 pid_t 与字符串进行比较?
  • @KeineLust 你当然是对的。更新了答案
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多