2016-11-14 65 views
0

但问题是我通过该方法发送之前打印的PID和在打印方法中打印的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); 

    } 
    } 

的输入方法只是需要来自用户的输入。 标记化方法使用strtok方法标记输入。如果我输入kill(PID),它会进入方法killbyPIDprocess(ptr,pid),其中ptr是包含所有结构进程指针的双指针。我存储过程信息,我创建一个。我在循环方法中打印的pid与我给它的输入相同,也就是说,我想通过一个pid来杀死我的进程,但是当我通过killbyPIDprocess方法传递此pid时,它会显示一些其他值。我还没有开始真正处理kill code,因为它一直给我提供错误。我使用打印语句来跟踪我的代码有多少工作。我对C比较陌生,自学成功,请指出错误。

+0

如果我在killbyPIDprocess()中使用* p或p,那并不重要。 p显示垃圾值 – Sobiaa

回答

1

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

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

+0

谢谢。那么如何比较pid_t和字符串? – Sobiaa

+0

@KeineLust你当然是正确的。更新了回复 – Ari0nhh

+0

非常感谢。 atoi作品:D – Sobiaa