什么是服务?
通常我们将常驻于内存等待用户请求或者定时执行任务的程序称作服务。linux系统下有的服务程序,一种是守护进程一种是后台进程
后台进程
通常情况下程序是默认在前台执行的,占用当前shell,用户无法继续使用当前shell。通过在启动参数的时候加一个'&' 可以让程序在后台执行
但是后台进程会随着Shell的退出而结束。因此要使用后台进程作为服务必须保证shell是一值存在,显然在生产环境中这种情况是不稳定的
守护进程
要让一个进程永远都是以后台方式启动,并且不能受到Shell退出影响而退出,传统做法是将其创建为守护进程(daemon)。守护进程值得是系统长期运行的后台进程。守护进程信息通过ps –a无法查看到,需要用到–x参数。
下面我们开始我们的第一个服务程序
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
cout <<"server is begin" << endl;
while(true)
{
cout <<"server is running..." << endl;
sleep(1);
}
return 0;
}
编译程序
[liujinchun@localhost test]$ g++ server.cpp -o server
执行程序
[liujinchun@localhost test]$ ./server
server is begin
server is running...
server is running...
server is running...
server is running...
通过while(true) 是我们的程序在执行后不会停止,然后我们在循环中加入了sleep函数,然我们的程序间歇性的休眠,释放对CPU的占用,否则会占用大量的CPU资源(CPU 100%)
好了,现在我们通过CTRL+C 来结束程序。
下面我们给这个服务程序增加一些功能。
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
cout <<"server is begin" << endl;
while(true)
{
cout << "server is running..." << endl;
int a = 0;
cout<< "请输入被加数:" <<endl;
cin >> a;
int b = 0;
cout<< "请输入加数:"<<endl;
cin >> b;
cout << a << "+" << b << " = " << a+b << endl;
sleep(1);
}
return 0;
}
编译程序
[liujinchun@localhost test]$ g++ server.cpp -o server
执行程序
[liujinchun@localhost test]$ ./server
server is begin
server is running...
请输入被加数:
3
请输入加数:
2
3+2 = 5
server is running...
请输入被加数:
5
请输入加数:
3
5+3 = 8
server is running...
请输入被加数:
我们为这个程序增加了一个等待用户输入两个数并求和的功能。它基本上满足了我们对于服务的基础定义:长期存在 并且完成对用户的请求。