1

我是 C Linux 编程的新手,为了练习,我试图从进程 ID 中获取可执行名称。如果我自己提供进程 ID,那么它可以正常工作,但如果进程 ID 在 while 循环中动态提供,则 readlink 返回 -1。任何人都可以帮助我,任何帮助表示赞赏。

char exe[1024];
    int ret;
char *tempBuffer = calloc(1000,sizeof(char));
int result2 = sprintf(tempBuffer,"/proc/%d/exe", pid);
printf("%s\n", tempBuffer);

ret = readlink(tempBuffer,exe,1024);

if(ret ==-1) {
    fprintf(stderr,"ERRORRRRR\n");
    exit(1);
}
exe[ret] = 0;
printf("I am %s\n",exe);
free(tempBuffer);



while (running)
{
    recvmsg(sock_fd, &msg, 0);
    SYSCALL *data = (SYSCALL *)NLMSG_DATA(nlh);


    char *pname = get_process_name_by_pid(data->pid);


    printf("%i,%lu,%i,%s\n", data->sys_id, data->inode, data->pid, pname);
    insert_trace(conn, data->sys_id, data->inode, data->pid, pname);

    memset(NLMSG_DATA(nlh), 0, sizeof(SYSCALL));

}


void insert_trace(PGconn *conn,int sys_id, int memaddr, int pid, char* pname)
{          

    char * buffer = calloc(1000,sizeof(char));

    char exe[1024];
        int ret;
    char *tempBuffer = calloc(1000,sizeof(char));
    int result2 = sprintf(tempBuffer,"/proc/%d/exe", pid);
    printf("%s\n", tempBuffer);

    ret = readlink(tempBuffer,exe,1024);

    if(ret ==-1) {
        perror("ERRORRRRR\n");
        exit(1);
    }
    exe[ret] = 0;
    printf("I am %s\n",exe);
    free(tempBuffer);

    int result = sprintf(buffer, "INSERT INTO trace (datetime,syscall_id,memory_address,process_name,process_id) VALUES (CURRENT_DATE,  %d, %d, '%s', %d)", sys_id, memaddr, pname, pid);



PGresult *res = PQexec(conn, buffer);

free(buffer);



    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
    printf("%d\n", 303030); 
        do_exit(conn, res);
    }else{
    printf("%d\n", 404040); 
    }
        PQclear(res);



}
4

0 回答 0