/proc/[pid]/cmdline file size

2019-02-21 01:22发布

i'm trying to get the filesize of the cmdline file in proc/[pid]. For example porc/1/cmdline. The file is not empty, it contains "/sbin/init". But i get file_size = 0.

int main(int argc, char **argv) {
    int file_size;
    FILE *file_cmd;
    file_cmd = fopen("/proc/1/cmdline", "r");
    if(file_cmd == NULL) {
        perror("proc/1/cmdline");
        exit(1);
    }else {
        if(fseek(file_cmd, 0L, SEEK_END)!=0) {
            perror("proc/1/cmdline");
            exit(1);
        }
        file_size = ftell(file_cmd);
    }
    printf("fs: %d\n",file_size);
    fclose(file_cmd);
    }

Regards

标签: size fopen proc
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-21 01:45

That's normal. /proc files (most of them, there are a few exceptions) are generated by the kernel at the moment you read from them. That means it's impossible to know the size before reading from the file. Think of it as Quantum Mechanics on files. You won't get a state unless you read the information, but there's no guarantee that reading again will give you the same information twice ;-)

In other words, the EOF is only generated when you try to read it. It's not there before that, so there's no way a file size can be determined.

This is really just communication with the kernel disguised as file I/O.

查看更多
登录 后发表回答