有人可以帮我吗?为什么会弹出运行时错误? 预先感谢:) 我不太擅长 C++。
#include <iostream>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<string.h>
#include<unistd.h>
#define KEY 123456
using namespace std;
int main()
{
int shmid=shmget(KEY, 128, 0666);
char* addr1=(char*)shmat(shmid, 0, 0);
strcpy(addr1, "Hello");
int pid=fork();
if(pid!=0)
{
char* addr2=(char*)shmat(shmid,0,0);
std::cout<<"\n"<<addr1;
std::cout<<"\n"<<addr2;
sleep(2);
std::cout<<"\n"<<addr1;
std::cout<<"\n"<<addr2;
int rval=shmdt(addr2);
std::cout<<"\n"<<addr1;
std::cout<<"\n"<<addr2;
}
else
{
strcpy(addr1, "World");
}
return 0;
}
有人可以帮我吗?为什么会弹出运行时错误? 预先感谢:) 我不太擅长 C++。 有人可以帮我吗?为什么会弹出运行时错误? 预先感谢:) 我不太擅长 C++。 抱歉,我必须这样做才能使内容更大。
基本上,有两个错误需要修复:
shmget
和 shmat
的错误。这不是很严重,但在某些情况下可能会导致
Runtime Error
。
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <cstdlib> // For exit()
//For ease of importing libraries, I use #include<bits/stdc++.h>, it imports everything for us
#define KEY 123456
using namespace std;
int main()
{
int shmid = shmget(KEY, 128, 0666 | IPC_CREAT);
if (shmid < 0) {
perror("shmget failed");
exit(1);
}
char* addr1 = (char*)shmat(shmid, 0, 0);
if (addr1 == (char*)(-1)) {
perror("shmat failed");
exit(1);
}
strcpy(addr1, "Hello");
int pid = fork();
if (pid < 0) {
perror("fork failed");
exit(1);
}
if (pid != 0) // Parent process
{
char* addr2 = (char*)shmat(shmid, 0, 0);
if (addr2 == (char*)(-1)) {
perror("shmat failed in parent");
exit(1);
}
std::cout<<"\n"<<addr1;
std::cout<<"\n"<<addr2;
sleep(2);
std::cout << "\naddr1: " << addr1;
std::cout << "\naddr2: " << addr2;
// Detach from shared memory
shmdt(addr2);
}
else // Child process
{
strcpy(addr1, "World");
}
// Detach from shared memory in both processes
shmdt(addr1);
return 0;
}