C ++标准支持进程吗? [英] Does the C++ standard support processes?
问题描述
我知道C ++ 11增加了对线程的支持。例如:
#include< iostream>
#include< thread>
void bar()
{
std :: cout< 谷仓;
}
int main()
{
std :: thread thread(bar);
thread.join();
return 0;
}
但是,有没有办法执行
在单独的进程中的功能?
不,c ++标准特别是C ++ 11)没有任何过程的概念(因此我不能给你一个更合理的引用,作为搜索结果来自最流行的和当前最新的c ++文档网站) p> 我也不知道过程支持计划用于下一个标准版本C ++ - 17(aka C ++ - 1z)。至少维基百科网站没有提及。 有一个流行的实现是为了提升, 你通常不能写可移植代码在裸机系统上运行,只有一个进程
但是,有没有办法执行
bar()
函数在一个单独的进程?
#include< iostream>
#include< unistd.h>
#include< sys / wait.h>
void bar()
{
std :: cout< 谷仓;
}
int main(int argc,char ** argv)
{
pid_t pid = fork();
if(pid == 0)
{
//子进程
bar();
}
else if(pid> 0)
{
//父进程
wait(NULL);
}
else
{
// fork failed
std :: cerr<< fork()failed! << std :: endl;
return 1;
}
return 0;
}
看到许多点,创建一个额外的过程来执行一个简单的函数。在这种情况下,创建一个进程会产生很多不需要的开销。
好吧,如果你想使用 exec()
函数系列是一个不同的用例。
我建议坚持使用 std :: thread
s。
I know C++11 added support for threads. For example:
#include <iostream>
#include <thread>
void bar()
{
std::cout << "bar()\n";
}
int main()
{
std::thread thread(bar);
thread.join();
return 0;
}
However, is there a way to execute the bar
function in a separate process? If not, is there any discussion on whether such a feature should be added?
Note: I'm aware of the possibility of using platform independent libraries and I'm just curious if C++ supports this directly or will in the future.
No, the c++ standard (particularly C++11) doesn't have any notion of a process (hence I can't give you a more reasonable reference here as a search result from the most popular and currently most up to date c++ documentation site).
I'm also not aware that process support is planned for the next standard version C++-17 (aka C++-1z). At least the Wikipedia Site doesn't mention it.
There is a popular implementation that was proposed for boost, but that never was drawn for a C++ standard proposal.
You usually can't write portable code to run on bare metal systems, where only one process exists.
However, is there a way to execute the
bar()
function in a separate process?
The simplest option to do that is to fallback to fork()
and wait()
as specified by the POSIX Open Group:
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
void bar()
{
std::cout << "bar()\n";
}
int main(int argc, char **argv)
{
pid_t pid = fork();
if (pid == 0)
{
// child process
bar();
}
else if (pid > 0)
{
// parent process
wait(NULL);
}
else
{
// fork failed
std::cerr << "fork() failed!" << std::endl;
return 1;
}
return 0;
}
Though I don't see much of a point to create an extra process to execute a simple function. Creating a process creates a lot of overhead you don't want in such case.
Well, if you want to start another program using functions from the exec()
function family that's a different use case.
I'd recommend sticking to std::thread
s for your example.
这篇关于C ++标准支持进程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!