gpt4 book ai didi

c - 消息队列fork + execlp + ftok的用法

转载 作者:太空宇宙 更新时间:2023-11-04 04:48:58 25 4
gpt4 key购买 nike

这里的主要目的是通过执行这个命令来创建一个消息队列:./create_msg_queue fileForQueue

如果文件 fileForQueue 不存在,我们要创建它。

关于我的代码,如果文件不存在,我会得到这个错误

ftok: No such file or directory

那么如何在使用文件名调用 ftok() 之前创建此文件?

提供的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

// IPC and KEYS -------------
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
//---------------------------

#define _XOPEN_SOURCE

// message structure
typedef struct {

// id message
long type;

// Size : 12 bytes
double mesure;
pid_t pidClient;

} message_t;

int main (int argc, char * argv []) {

key_t key;
message_t message;
int file;
int pid;

// Check arg number
if (argc != 2) {
fprintf(stderr, "Syntaxe : %s fichier_clé\n",argv[0]);
exit(EXIT_FAILURE);
}

// Create the empty file given in parameter
if ((pid = vfork()) == -1)
{
perror("fork");
exit(1);
}

if (pid)
{
// code replacement to create the FILE
execlp("touch", "touch", argv[1], NULL);
perror("execlp");
exit(1);
}else
{
// Trying to wait for the forked() process to finish its file creation
wait (NULL);

// I GET ERROR HERE IF THE FILE DON'T EXIST BEFORE I LAUNCH THE PROGRAM
// Create key with the file given in parameter and then created
if ((key = ftok(argv[1], 0)) == -1) {

// errNo value
perror("ftok");
exit(EXIT_FAILURE);
}

// Create message queue
if ((file = msgget(key, IPC_CREAT | 0666)) == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}

// Registering message content
message.type = 1;
message.mesure = -1;
message.pidClient = getpid();

// Sending message
if (msgsnd(file, (void *) & message, 12, 0) <0) {
perror("msgsnd");
exit(EXIT_FAILURE);
}


}
return EXIT_SUCCESS;
}

在此先感谢您的帮助。我挣扎:)

最佳答案

key_t ftok(const char *path, int id);


ftok(argv[1], 0))

Only the low-order 8-bits of id are significant. The behavior of ftok() is unspecified if these bits are 0.

另请注意,您必须

#define _XOPEN_SOURCE

一开始

关于c - 消息队列fork + execlp + ftok的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899428/

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