为什么我在使用 vfork() 时出现错误?
这是我的代码...我不知道为什么我收到错误段...有人可以向我解释原因吗?
#include <iostream>
#include <string>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int globalVariable = 2;
main()
{
string sIdentifier;
int iStackVariable = 20;
pid_t pID = vfork();
if (pID == 0) // child
{
// Code only executed by child process
sIdentifier = "Child Process: ";
globalVariable++;
iStackVariable++;
cout << "PROCESO NUMERO"<<getpid()<<sIdentifier;
// printf("Proceso hijo: PID %d - PPID %d\n", getpid(), getppid());
cout << " Global variable: " << globalVariable;
cout << " Stack variable: " << iStackVariable << endl;
return (0);
}
else if (pID < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
return (1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
// executed only by parent
cout << sIdentifier;
cout << " Global variable: " << globalVariable;
cout << " Stack variable: " << iStackVariable << endl;
return (0);
}
This is my code... I don't know why I'm get an error segment... could somebody explain the reason to me?
#include <iostream>
#include <string>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int globalVariable = 2;
main()
{
string sIdentifier;
int iStackVariable = 20;
pid_t pID = vfork();
if (pID == 0) // child
{
// Code only executed by child process
sIdentifier = "Child Process: ";
globalVariable++;
iStackVariable++;
cout << "PROCESO NUMERO"<<getpid()<<sIdentifier;
// printf("Proceso hijo: PID %d - PPID %d\n", getpid(), getppid());
cout << " Global variable: " << globalVariable;
cout << " Stack variable: " << iStackVariable << endl;
return (0);
}
else if (pID < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
return (1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
// executed only by parent
cout << sIdentifier;
cout << " Global variable: " << globalVariable;
cout << " Stack variable: " << iStackVariable << endl;
return (0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个有用吗? 请注意有关变量修改的警告。
Is this of use ? Note the caveats surrounding modification of variables.
如果您 vfork() 两个进程共享地址空间。 如果您要立即在子进程中执行另一个进程,您可能应该只使用 vfork() 。 创建系统调用的原因是为了避免复制父进程地址空间中的每个页面而导致子进程执行时丢弃所有这些映射的开销。 对于您的情况,请改用 fork() 。
If you vfork() both processes are sharing an address space. You should probably only use vfork() if you are going to exec another process pretty much immediately in the child. The reason the system call was created was to avoid the overhead of copying every page in the parent process's address space only to have all those mappings discarded when the child exec's. For your case, use fork() instead.