gpt4 book ai didi

c - 我正在使用 PID 创建一个终止进程

转载 作者:行者123 更新时间:2023-11-30 15:03:44 24 4
gpt4 key购买 nike

但问题是我在通过该方法发送之前打印的 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 相同,即我想通过它杀死进程的一个 pid,但是当我通过killbyPIDprocess 方法传递这个 pid 时,它显示了一些其他值。我还没有开始实际研究终止代码,因为它一直给我错误。我使用打印语句来跟踪我的代码有多少在工作。我对 C 语言比较陌生,而且是自学的,所以请指出错误。

最佳答案

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

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

关于c - 我正在使用 PID 创建一个终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40582898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com