command我不知道这个值大小为多少,上面这两个函数可以实现无论多大都可以存储或取值么
时间: 2024-04-15 10:27:52 浏览: 20
对于存储和获取不确定大小的字符串,你可以使用动态内存分配来处理。
在`SetGetTCPCommand`函数中,你可以将命令字符串的长度作为参数传递给函数,并使用动态内存分配来存储命令。这样可以确保足够的空间来存储任意长度的字符串。
以下是修改后的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int SetGetTCPCommand(const char *mode, char **command, size_t commandSize) {
key_t key = ftok(".", 1234);
int shmid = shmget(key, commandSize, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
return 0;
}
char *sharedData = (char *)shmat(shmid, NULL, 0);
if (sharedData == (void *)-1) {
perror("shmat");
return 0;
}
if (strcmp(mode, "set") == 0) {
strncpy(sharedData, *command, commandSize - 1);
} else if (strcmp(mode, "get") == 0) {
*command = malloc(commandSize);
strncpy(*command, sharedData, commandSize);
} else {
printf("Invalid mode\n");
return 0;
}
shmdt(sharedData);
return 1;
}
```
在调用`SetGetTCPCommand`函数时,你可以传递命令字符串的大小作为参数,如下所示:
```c
char *command1 = "echo `uci get m_system.usesiminfo.operator;uci get m_system.usesiminfo.card_slot; \
uci get m_system.usesiminfo.iccid;uci get m_system.usesiminfo.lock;uci get m_system.system.simnum`";
size_t command1Size = strlen(command1) + 1;
char *command2 = "echo `uci get m_system.sim1.operator;uci get m_system.sim1.card_slot;uci get m_system.sim1.iccid; \
uci get m_system.sim2.operator;uci get m_system.sim2.card_slot;uci get m_system.sim2.iccid; \
uci get m_system.sim3.operator;uci get m_system.sim3.card_slot;uci get m_system.sim3.iccid; \
uci get m_system.sim4.operator;uci get m_system.sim4.card_slot;uci get m_system.sim4.iccid`";
size_t command2Size = strlen(command2) + 1;
SetGetTCPCommand("set", &command1, command1Size);
SetGetTCPCommand("set", &command2, command2Size);
```
通过这种方式,你可以确保无论命令字符串的大小是多少,都能正确地存储和获取值。
希望这次能解决你的问题!如果你还有其他问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)