精华内容
下载资源
问答
  • launchd
    2015-09-15 15:30:17

    Mac系统下通用的进程管理器,是Mac系统下非常重要的一个进程。一般来说该进程不允许直接以命令行的形式调用。只能通过其控制管理界面,launchctl来进行控制。

    launchd主要功能是进程管理。可以理解成是一个常驻在后台的进程,根据用户的配置,来响应特定的系统事件。launchd既可以用于系统级别的服务,又可以用于个人用户级别的服务。

    在launchd的语境中,常驻进程有两种,一种称为是daemon,也就是我们常说的守护进程,这种一般对所有用户都有相同的行为,响应相同的事件,始终运行于后台,没有前台交互界面。另一种称为是agent,这种是用户级别的服务进程,一般以用户的身份运行。

    • ~/Library/LaunchAgents 用户的进程
    • /Library/LaunchAgents 管理员设置的用户进程
    • /Library/LaunchDaemons 管理员提供的系统守护进程
    • /System/Library/LaunchAgents Mac操作系统提供的用户进程
    • /System/Library/LaunchDaemons Mac操作系统提供的系统守护进程

    以上是launchd的相关配置的存放目录,可以看到,一般我们个人编写的守护进程,都应该放到~/Library/LaunchAgents目录里面。

    更多相关内容
  • 有关常规语法,请参见 ,但对于特定于macOS的实现,请参阅man launchd.plist ,该实现在许多方面都是一个子集。 打开从公共端口50122到本地端口22的UPnP端口,以进行SSH。 加载后,它将尝试每5分钟运行一次,直到...
  • 推出了一个launchd.plist编辑器。 launchd是cron的强大而灵活的替代品,但是手动编写plist文件可能很困难。 这个程序使它更容易。 YIBYABS:是的,我建立了另一个Bootstrap网站!有什么好处吗? 是的。贡献叉修补...
  • Ruby-Launchd-使用Ruby控制Mac OS X服务Ruby-Launchd就像launchctl(或著名的午餐)一样。 它使您可以使用Ruby在Mac OS X上轻松创建,启动和停止服务。安装将此行添加到您的应用程序的Gemfile中: gem 'launchd' ...
  • 一个launchd守护进程 一个简单的咆哮通知器 一个 osquery 配置 它需要: 操作系统 咆哮(接受连接) 它监视启动项更改、内核扩展更改和启动项更改。 它没有列举所有已知的恶意软件位置,但确实涵盖了最常见的位置...
  • 我使用创建了一个launchd可以使用的属性列表,如果您没有或使用Lingon,请在此处复制。 <? xml version = " 1.0 " encoding = " UTF-8 " ?> <! DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ...
  • 现在不再需要这个,因为 homebrew 的 privoxy 附带了一个 launchctl Privoxy Launchctl 为什么? 我用自制软件。 当您安装 Privoxy 时,它不会创建它。...launchctl start org.privoxy.launchd.privoxy
  • 用于在 OS X 上运行开源 puppet 的包装器脚本和 launchd。 要使用此包装器,请执行以下操作: 将 puppet_run.py 放入 /usr/local/bin 并确保它具有执行权限 编辑 com.company.puppet_run.plist 以匹配您的公司...
  • Ruby推出代理 一个可以轻松使用 launchd 的库简介 require 'launch_agent'agent = LaunchAgent :: Daemon . new ( 'ruby' , '/path/to/foo.rb' , 'arg1' , 'arg2' )# loadagent . load# unloadagent . unloadCLI % ...
  • MacOS:launchd .plist文件

    launchd官方文档>>
    详解文章1>>
    详解文章2>>

    什么是launchd

    来自于官方文档:”Wikipedia defines launchd as "a unified, open-source service management framework for starting, stopping and managing daemons, applications, processes, and scripts. Written and designed by Dave Zarzycki at Apple, it was introduced with Mac OS X Tiger and is licensed under the Apache License."

    可以理解为,launchd是一套统一的开源服务管理框架,它用于启动、停止以及管理后台程序、应用程序、进程和脚本。launchd是macOS第一个启动的进程,该进程的PID为1,整个系统的其他进程都是它创建的。当launchd启动后,它会扫描/System/Library/LaunchDaemons/Library/LaunchDaemons中的plist文件并加载他们;当输入密码登录系统后,launchd会扫描/System/Library/LaunchdAgents/Library/LaunchAgents~/Library/LaunchAgents这三个目录中的plist文件并加载它们。每个plist文件都是一个任务,加载不代表立即运行,只有设置了RunAtLoadtruekeepAlivetrue时,才会加载并同时启动这些任务。

    Daemons和Agents

    守护进程,英⽂叫Daemon,守护进程其实就是在后台运⾏的程序,它没有界⾯,你看不到它,⼀般使⽤命令来对它进程管理控制,守护进程常被设置为开机⾃动启动(当然也可以开机后⼿动⽤命令启动),很多软件的“服务器端”⼀般都是以守护进程的⽅式运⾏,⽐如数据库 、内存缓存 、Web服务器 等等都是以守护进程⽅式运⾏的,它们通过“接⼝”对外提供服务(如Unix socket / tcp ⽅式等等)。
    DaemonsAgents都是launchd所管理的后台程序,它们的区别是Agent是属于当前登录⽤户(就是你开机后输⼊密码时的那个⽤户名),它们是以当前登录的⽤户权限启动的,⽽Daemon则属于root⽤户,但由于有root⽤户权限,所以它可以指定以什么⽤户运⾏,也可以不指定(不指定就是以root⽤户运⾏)。

    launchd如何管理后台进程

    launchd是通过以“.plist”后缀结尾的xml⽂件来定义⼀个程序的开机⾃启动的,我们⼀般称它为plist⽂件。

    编写一个简单的.plist配置文件,启动一个Agent进程

    1.使用XCode编写一个需要运行的程序launchd_test

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSProcessInfo *proc = [NSProcessInfo processInfo];
            NSArray *args = [proc arguments];
            // insert code here...
            NSLog(@"%@",args[1]);
            NSLog(@"Hello, World!");
        }
        return 0;
    }
    

    ctrl +B编译成一个可执行程序launchd_test

    2.编写.plist配置文件

    launchd会读取.plist文件,进而决定如何启动该进程

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      3 <plist version="1.0">
      4     <dict>
      5         <key>Label</key>
      6         <string>local.launchd_test.app</string>
      7         <key>Program</key>
      8         <string>/Users/mac/Documents/launchd_test</string>
      9         <key>ProgramArguments</key>
     10         <array>
     11                 <string>/Users/mac/Documents/launchd_test</string>
     12                 <string>happy</string>
     13         </array>
     14         <key>RunAtLoad</key>
     15         <true/>
     16     </dict>
     17 </plist>
    

    Label为需要启动的进程设置一个标签,这里起名为local.launchd_test.app
    Program设置为需要启动的可执行程序的路径
    ProgramArguments设置为程序运行需要的参数,第一个参数即为main函数中的argv[0]
    RunAtLoad设置为是否在加载时启动,设置为true则在launchd加载时就启动,false则需要手动启动
    将此文件命名为local.launchd_test.app.plist 对于用户代理进程,我们将.plist文件放到~/Library/LaunchAgents.文件中,对于守护进程,我们将其放到/Library/LaunchDaemons文件中

    3.加载、卸载、启动、停止、查看launchd列表

    列出所有由launchd管理的进程

    launchctl list 
    

    查看某个具体的进程

    host:~ user$ launchctl list | grep com.example.app
    -	2	com.example.app
    

    1.首先,创建完.plist文件后,需要加载该文件,

    launchctl load ~/Library/LaunchAgents/local.launchd_test.app.plist
    

    正常不会输出任何东西,如果输出

    Load failed: 5: Input/output error
    Try running `launchctl bootstrap` as root for richer errors.
    

    可以尝试

    launchctl unload ~/Library/LaunchAgents/local.launchd_test.app.plist
    launchctl load ~/Library/LaunchAgents/local.launchd_test.app.plist
    

    2.launchd启动代理进程

    launchctl start local.launchd_test.app
    

    此时,可以通过launchctl list查看到launchd_test的进程号

    launchctl list | grep local.launchd_test.app
    

    卸载、关闭命令

    launchctl unload ~/Library/LaunchAgents/local.launchd_test.app.plist
    launchctl stop local.launchd_test.app
    

    通过launchd启动进程后,bash上看不到输出,如果需要查看输出,需要将NSLog输出重定向到指定文件夹===》

    展开全文
  • 资源分类:Python库 所属语言:Python 资源全名:launchd-0.1.1-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
  • 启动OS X launchd plist 管理安装打开终端并运行以下命令: curl suderman.github.io/launchup/install | sh
  • 024.关于launchd中消息队列逻辑问题允许任意的mach message控制的问题1
  • launchd-842.92.1.tar.gz

    2021-06-07 19:29:15
    苹果 macosx launchd src
  • Mac OS X: Launchd in Depth

    2019-09-18 19:05:01
    Note: a old article topic, just for reference. Launchd in Depth Friday, July 08 2005 @ 04:52 pm MDT Contributed by: macshome Views: 1...
    Note: a old article topic, just for reference.

    Launchd in Depth

    Articles When Apple announced the UNIX based Mac OS X lots of sysadmins took notice. For years the Linux crowd had been trying, and failing, to get UNIX to the general desktop audience. I ran Linux for a while on Beige G3 and it required a trip to Open Firmware and a bootconf loader on a floppy to get it going at the time. When I installed my first Rhapsody build, all I had to do was put the Caps Lock key on to get all the UNIXy goodness. The times, they were a changing.

    Fast forward several years and Apple is now the highest volume UNIX vendor in the world. Furthermore the base of Mac OS X is open source and Apple uses many OSS projects in Darwin. Apple also has created projects and turned them out into the OSS world. (I'm well aware of the issues that some in the community have with Apple's OSS participation level, it's just not the focus of this article.) Recently Apple has loosed a new beast onto the world and it's knocked many people for a loop.

    Welcome, launchd. Seriously.

    Read on for more...

    Apple's position as the leading UNIX vendor, and as a unified solution provider, gives them some unique opportunities. One of these has been to take a look at some of the traditional mishmashes of UNIX and try to sort them out a bit. Lookupd is one of these efforts and it provides general resolver services for everything from DNS to GID lookups on Mac OS X. Applications don't need to know anything about how the machine is configured, they just ask lookupd for the info. If you look at Mac OS X, and OpenStep before it, you will see that the OS has been striving for this sort of consolidation of services for a while now.

    With Tiger, Apple has started to tackle the system of files and processes that start a UNIX system. Before it was often hard to tell how everything got cranked up. Was a daemon started by SystemStarter? Was it started by xinetd? Was it started by RC? Was it started by cron? Was it started by init or mach_init? Was it started by watchdog? Even worse, what if you needed to add a service? It was fairly clear that SystemStarter was what Apple wanted for startup items, but what about launch on demand? Xientd seems obvious here, but not everything can be launched by xinetd. What about service control? How do you easily start and stop services so that the rest of the system is aware of them?

    In all honesty, this is a problem that Microsoft had figured out a while ago. There is nothing in Panther and earlier that compares to the Services control panel, or MMC snap-in, on Windows. Mac OS X still doesn't have that easy level of control, but the foundations are now there with launchd and its buddy launchctl. (Incidentally, this is a great opportunity for an industrious AppleScripter to whip out a Studio app.)

    Meet the team
    When Apple decided to overhaul the 30 year old system for starting and maintaining processes on UNIX it had to think big. launchd can do the jobs of init, mach_init, xinetd, RC, SystemStarter, watchdog, and cron. It is Apple's stated intention that they want to eliminate all of those services in favor of launchd at some point in the future. There are two main programs in the launchd system, launchd and launchctl. Briefly:

    launchd manages the daemons at both a system and user level. Similar to xinetd, launchd can start daemons on demand. Similar to watchdogd, launchd can monitor daemons to make sure that they keep running. launchd also has replaced init as PID 1 on Mac OS X and as a result it is responsible for starting the system at boot time.

    launchctl is our window into the world of launchd. Using launchctl we can load and unload daemons, start and stop launchd controlled jobs, get system utilization statistics for launchd and its child processes, and set environment settings.

    A third, and the most confusing, part of the system are the plist files that define the services to be loaded into launchd with launchctl. Stored in the LaunchAgents or LaunchDaemons of any Library, the XML files have around thirty different keys that can be set, and the syntax is not very pretty. All of the options are laid out in the launchd.plist man page, which hides them nicely by using an obscure name. Even after reading the substantial man page you still have no real clear idea of how to use the keys to construct a valid plist, and that's where thieving from the default Apple plists comes in handy.

    Time to dig in...

    launchd
    When it comes down to it, launchd has two main tasks. The first is to boot the system and the second is to load and maintain services. Let's take a look at the boot part of the job first.

    When Mac OS X boots it goes through quite a few steps. Here is a very simplified view of the 10.4 system startup.

    1. The BootROM activates, does its thing to the hardware, and then loads BootX.
    2. BootX loads the kernel, spins the gear, loads any needed kexts, and then the kernel loads launchd.
    3. launchd then runs /etc/rc, scans through /System/Library/LaunchDaemons and /Library/LaunchDaemons and acts on the plists as needed, and finally starts the loginwindow.

    Easy huh?

    The first one we should look at here is step 2. This is a huge change for Mac OS X, and *NIX in general, in that some flavor of init is not loaded here. Indeed, launchd is now PID 1 on Mac OS X.

    In step three, launchd scans through a few different directories for jobs to run. There are two different folders types that are scanned. The LaunchDaemons folders should contain items that will run as root, generally background processes. The LaunchAgents folders should contain jobs, called agent applications, that will run as a user or in the context of userland. Often these can be scripts, other foreground items, and they can even include a user interface. When we get to our example we will be creating a user-specific LaunchAgent job. These directories are all kept in the typical Libraries of Mac OS X.

    launchd is very different from SystemStarter in that it may not actually launch all the daemons at boot time. Key to launchd, and similar to xinted, is the idea of launch on demand daemons. When launchd scans through the job plists at boot time it reserves and listens on all of the ports requested by those jobs. If so indicated in the plist by the "OnDemand" key, the daemon is not actually loaded at the time. Rather launchd will listen on the port, start the daemon when needed, and shut it down when it is not. After a daemon is loaded, launchd will keep track of it and make sure it is running if needed. In this way it is like watchdogd, and shares watchdogd's requirement that processes do not attempt to fork or daemonize on their own. If a process goes into the background launchd will lose track of it and attempt to relaunch it.

    This is why Tiger boots so fast. The system only has to register the daemons that are to run, not actually launch them. In fact the progress bar that appears is just a placebo that doesn't really show anything other than the passage of time. This explains why the bar never reaches the end before the login window appears sometimes. (For fun you can run it any time you like by executing /usr/libexec/WaitingForLoginWindow.) In addition to incoming requests, there are other ways to define launch on demand and we will take a look at them in just a few moments.

    The hardest part to manage during a launchd boot is dependancies. SystemStarter had a very simple system of dependancies that used the "Uses", "Requires", and "Provides" keys in the plist of a startup item. There are two main strategies when creating launch dependancies on 10.4. You can use IPC which will allow the daemons to talk amongst themselves to work it out or you can watch files or paths for changes. Using IPC is much more subtle than the SystemStarter's keys and requires more work from the developer, but it should lead to cleaner and quicker startups. It does however, put dependancies out of the reach of many admins, myself included, as we aren't actually creating daemons. If you have a timed script that needs to be run you can still use a SystemStarter item at this time. Don't get too comfortable with that though as it has been deprecated in 10.4

    plist Time
    When launchd scans a folder, or a job is submitted with launchctl, it depends on a properly formatted plist file that describes the job to be run. This is, for most sysadmins, is the most difficult area of launchd to grasp. SystemStarter used simple shell scripts to launch daemons. launchd requires the admin to be able to properly format an XML file and while not exceedingly difficult, it can be confusing.

    The first stop you should make is the man page for launchd.plist. Give it a good read and don't worry if it makes your eyes bug out. It does that to everyone at first. At the very end it gives an example of a plist for your perusal. This example is very simple but it breaks down some of the keys you will become familiar with. At a minimum there are two required launchd.plist keys. "Label" is the string that defines how launchd will refer to the job, and "ProgramArguments" breaks down how to execute your program. That's it, but it's not enough to generate a useful job. Really we want to toss a few more keys in there to add to the flexibility of the job and to make it more efficient.

    Some other useful keys:
    "UserName" allows you to run the job as a user other than the one who submitted it to launchd. "inetdCompatibility" indicates that the daemon expects to be run as if it was launched by inetd. "Program" allows you to name the path to your executable. By using this key you can save the ProgramArguments key for, well, flags and arguments. "OnDemand" is a boolean that will allow you to define if a job runs continuously or not. "RootDirectory" will let you chroot the job into another directory. "ServiceIPC" is where you specify if the daemon can speak IPC to launchd. "WatchPaths" allows you to have launchd start a job based on a path modification. "QueueDirectories" almost the same as a WatchPath, a queue will only watch an empty directory for new files. "StartInterval" Used to schedule a job that runs on repeating schedule. "StartCalendarInterval" You can use this to schedule jobs. The syntax is similar to cron. "HardResourceLimits" Will allow you to restrict the resources consumed by any job. "LowPriorityIO" Tells the kernel that this task is of a low priority when doing file system I/O. "Sockets" This array can be used to specify what socket the daemon will listen on for launch on demand. Check out the cool Bonjour key that can be used to register the socket with the mDNSResponder.
    Phew! That's not all of them, but I think that these represent a useful selection. Read the man page for all of them and the options to be used. Now that we know about some keys, lets do something neat with them.

    In our example were are going to create a very simple user agent application that moves files and folders from one directory to another. It's a very basic sort of idea, but it's also a good building block for more complex file processing.

    First we need to come up with the script that our launchd job will execute. For our purposes something simple like:
    
    #!/bin/bash
    
    mv /Users/josh/in/* /Users/josh/out/
    exit 0
    
    
    
    will work. It simply takes anything in the "in" directory and moves it to the "out" one. Stick it wherever you like. Since this is a user specific agent I just dropped it in my home folder and named it "mover".

    Now we need to create our launchd job plist. First create ~/Library/LaunchAgents, then go find a launchd plist file in /System/Library/LaunchDeamons that seems pretty similar to what you want to do. For this example I stole the cron plist and copied it to my new LaunchAgents folder. Fire up your editor of choice and start making changes.

    In the end we should have something that looks a bit like this:

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    	<key>Label</key>
    	<string>com.afp548.mover</string>
    	<key>OnDemand</key>
    	<true/>
    	<key>Program</key>
    	<string>/Users/josh/mover</string>
    	<key>ProgramArguments</key>
    	<array>
    		<string>mover</string>
    	</array>
    	<key>WatchPaths</key>
    	<array>
    		<string>/Users/josh/in</string>
    	</array>
    </dict>
    </plist>
    
    
    
    All we really needed to do was to give it a new label, modify the executable that is called, change the cron file's RunAtLoad key into an OnDemand one, and make the WatchPaths point to the correct place. Because we started with an existing file we don't need to worry about the header or figuring the structure out on our own. Why a WatchPaths key instead of a QueueDirectories key? The QueueDirectories depends on the directory being empty to look for added files. If you open the directory in the Finder it will make a .DS_Store file and throw your job into a horrible loop. The WatchPaths is a bit different in that it watches a path for modifications and doesn't require the directory to be empty. WatchPaths can also keep an eye on a file. Take a look at the default cron plist for a nice example of this.

    Note that in this example I also added a ProgramArguments key. I did this as it makes the job more flexible for future changes. Something to keep in mind with this key is that each flag or argument to be passed to the program must be in its own string of the array. The org.postfix.master.plist file is a good example of this. You can't simply say:
    
    <key>Program</key>
    	<string>/usr/libexec/postfix/master -e 60</string>
    
    
    
    but instead must use:
    
    <key>Program</key>
    	<string>/usr/libexec/postfix/master</string>
    	<key>ProgramArguments</key>
    	<array>
    		<string>master</string>
    		<string>-e</string>
    		<string>60</string>
    	</array>
    
    
    
    which can be a bit confusing at first, but is nothing too hard once you do it the first time. Really you should take a look at the default plists that Apple has in /System/Library/LaunchDaemons. They are full of good examples of just about everything that you might want to do. For example, the com.apple.periodic-daily.plist job controls running the daily periodic job. This used to be something that was controlled by cron, so it's a good way to see how to schedule something with launchd. Take a look:
    
    	<key>StartCalendarInterval</key>
    	<dict>
    		<key>Hour</key>
    		<integer>3</integer>
    		<key>Minute</key>
    		<integer>15</integer>
    	</dict>
    
    
    
    Be aware that launchd is nowhere near as flexible as Vixie cron. Luckily cron is still on the system for us to use if we wish.

    If all of this seems a bit scary still, there is a nice shareware GUI out there that can handle the file generation for you. Take a look at the Launchd Editor from codepoetry to see what it can do.

    Now that we have our executable and plist setup how do we load our new job into launchd? We could logout and back in, but that's a bit intrusive to just fire up a new service. This is where launchd's buddy, launchctl comes into play.

    Enter launchctl

    One of the big problems before launchd was that there was no easy or consistent way to control system services. SystemStarter was almost cool, but it never seemed to work properly in most cases for controlling services after startup. The problem with the other facilities for service control was that they are strewn across the OS with no central way to manage them. launchctl is Apple's way of fixing this.

    On its own, launchctl can take commands from the command line, from standard in, or operate in interactive mode. If you come up with a set of commands that you want to make permanent you can store them in ~/.launchd.conf or /etc/launchd.conf. By using these files you can setup the environment that launchd operates in at either a user or global level. You can use sudo launchctl to make easy changes on a global scale, something that you couldn't do on 10.3 and earlier.

    Let's start out with something simple though, loading our job. The syntax is basic, in our case:

    launchctl load ~/Library/LaunchAgents/com.afp548.mover.plist

    will load our job. We can confirm it's loaded with:

    launchctl list

    which will show us the launchd jobs that our user has submitted. If you want to see the system job list simply run the same command with sudo.

    Now that our job is loaded, try dropping something in your "in" folder. If all is well it will vanish and then appear in your "out" folder in a manner similar to this spiffy movie (H264 codec required). For what it is worth, the folder in the movie has a bunch of loose files in it and it's running on a 400 MHz G4. As you see the response time of launchd is great. Again this is a very simple example, but it's useful and is a great launching pad for bigger tasks. For example launchd could watch a drop folder for graphic files that it processes with sips and then ftp transfers to a web server. The options are practically endless.

    To remove a job we use the inverse of the load command...

    launchctl unload -w ~/Library/LaunchAgents/com.afp548.mover.plist

    Notice that I added the optional "-w" flag this time. This flag adds or removes the "disabled" key from the plist at the appropriate time. If you don't use this when unloading a job it will automatically load the next time you login or reboot, depending on where your job file is located. You use the same "-w" flag when loading the job to remove the disabled key automatically.

    Just like lookupd, you can also use launchctl in interactive mode. Simply run it without any arguments and you will be delivered to the launchd prompt. Type "help" to see the list of commands that you can issue. They are the same as if you were calling them directly, but now you don't need to keep typing launchctl over and over again. A standard ctrl-d will escape the launchd shell.

    If you want to view the resource usage of any particular job, or launchd as a whole, you can use the "getrusage" command. When using this command you need to specify if you are interested in launchd itself or its children. Again, you use sudo to see the global resource usage. So if I wanted to see the resource usage of all of launchd's kids:

    sudo launchctl getrusage children

    is all I need. If you change our demo job plist to use a QueueDirectories key rather than the WatchPaths one there is a very high probability that a race condition will appear. This can be really bad as it can run wild and suck up all the CPU time on your system. Which leads us right into our next launchctl subcommand.

    Using the "limit" command we can view and set limits on the launchd environment. With no resource specified this displays three columns representing the resources, their soft limits, and finally, their hard limits. Again you can use sudo to define or view these for the system as a whole. The limits you set with launchctl are the same limits you can set in a job plist, but they apply to the entire launchd environment rather than a single job. There are details in the launchd.plist or setrlimit man pages, but I'll list them briefly here:

    "cpu" The maximum CPU time, in seconds, to be used by a process. "filesize" The file size limit, in bytes, that a process may create. "data" The data segment size limit, in bytes, for the process. "stack" The stack segment size limit, in bytes, for the process. "core" The core file size limit, in bytes, for the process. "rss" This sets the resident set size that controls how much physical memory the process may have. The OS will prefer to reclaim memory from applications that are over their soft limit when things get tight. "memlock" The maximum size an app may lock into memory. "maxproc" The maximum number of processes for a particular user ID. "maxfiles" Obviously, the maximum number of open files for a process.

    To set these limits simply use the limit command but add a resource type and name a limit. If you only enter one number it will be used for both the soft and hard limits. If you want them to be different you need to enter both the soft and hard limits in order.

    launchctl limit maxfiles 256 512

    Will set the maxfiles limit to 512, while retaining the default soft limit of 256 files.

    There are other similar launchctl commands that we can use to set logging levels, change the stdout and stderr of launchd, set environment variables, or change the umask of launchd. For example if I wanted to redirect the stdout of just my launchd jobs to a file I could say:

    launchctl stdout /Users/josh/Library/Logs/launchd.out

    It is important to remember that these commands are job persistant, but not launchd persistent. Meaning that the general launchd settings will not survive a reboot. This is easy to fix by dropping a conf file in the appropriate place. For global settings you should use /etc/launchd.conf and for user settings you should use ~/.launchd.conf. Just enter your launchctl commands, without the launchctl part, in the file one line at a time. If I wanted to combine my two examples above into a permanent setting I would put:

    
    # This is my launchd.conf file.
    limit maxfiles 256 512<br>
    stdout /Users/josh/Library/Logs/launchd.out
    
    
    
    in the appropriate launchd.conf file.

    Concerns

    At this point you are probably thinking that launchd is pretty cool and you would be right, but I do have a few concerns.

    First of all launchd replaced init and xinetd with one process. This is a bit scary as we now basically have init listening in a bunch of different ways for something to tell it to start a job. The security implications of this aren't really known yet with launchd being as young as it is.

    Secondly, and in the same vein, launchd is process 1 and it has the potential to take down the whole system. I've already seen unconfirmed reports of a ssh scan on a network causing launchd to freak out and make systems inaccessible. Having at least some sort of resource limit set on jobs might help here.

    These risks and unknowns could have been minimized by gradually phasing launchd in, but Apple has chosen to drop it on us like a bomb. I know of people who are migrating services back to xinetd when they do installs. It's not because launchd is flawed, but because it is a bit of an unknown for the time being.

    That said I'm really excited by the potential of launchd. We are now one GUI away from a Windows-style "Services" utility.

    Wrapping up

    Wow, that was a lot to take in at once eh? launchd is here, and it is the future of service management on Mac OS X. Apple has opened the project in the hopes that other *NIX vendors will take a look at it and incorporate it into their own OSes. With launchd being the work of Jordan Hubbard it probably carries a bit more clout than other Apple OSS projects in the community. All in all it is the most aggressive attempt by anyone to reign in the herd of cats that booting and maintaining a UNIX system has become, and for that we should be standing and cheering.

    As always, have fun and read the man pages.

    man launchd
    man launchd.conf
    man launchd.plist
    man launchctl
    man launchd_debugd

    That last one is a nice little nugget, but it is a bit of a trick as the plist it references isn't installed by default. First you need to get the xml file from the darwin source here (Apple ID login required). Change its name from com.apple.launchdebugd.xml to com.apple.launchd_helperd.plist, copy it to /System/Library/LaunchDaemons, load it, and then point your web browser at port 12345 on the Mac in question to get a cool output of all loaded jobs and their settings.

    (If you don't have an Apple ID, or don't want to agree to the Apple Open Source license, I've put a copy of the finished launchd_helperd.plist in our file database. )

    ( Ed. note: For the ease of sharing, this document is released with the GFDL license as well as our regular Creative Commons license.)

    from:http://www.afp548.com/article.php?story=20050620071558293

    原文链接: http://blog.csdn.net/afatgoat/article/details/6212263

    转载于:https://my.oschina.net/junwong/blog/46602

    展开全文
  • 在Mac下没有像Linux那样有很多的关于init方面的工具,从init的发展历史https://en.wikipedia.org/wiki/Init上可以知道,Mac使用的是Launchd作为init管理工具,对应的命令工具为launchctl。 如果在Linux下创建一个自...

    背景:

    在Mac下没有像Linux那样有很多的关于init方面的工具,从init的发展历史https://en.wikipedia.org/wiki/Init上可以知道,Mac使用的是Launchd作为init管理工具,对应的命令工具为launchctl。

    如果在Linux下创建一个自启动服务可以使用Upstart、Systemd、Sysvinit,其中最简单和最古老的方式应该是Sysvinit,毕竟其支持Shell脚本,非常方便。而在Mac下,与Linux的做法不太一样,采用Launchd进行管理,其设置服务采用了plist文件进行对服务来描述,并通过配置好后放在/System/Library/LaunchDaemons或者/Library/LaunchDaemons,最后通过launchctl命令行使其生效,期间也可以直接通过launchctl来对服务进行操作,比如启动、停止等。

    详细的plist编写规范及介绍,参考:https://en.wikipedia.org/wiki/Launchd

    以下是关于Launchd的详细解释:

    Launchd是什么?

    Mac OS X从10.4开始,采用Launchd来管理整个作业系统的Services及Processes 。传统的UNIX会使用/etc/rc.*或其他的机制来管理开机时要启动的Startup Services,而现在的Mac OS X使用launchd来管理,它的Startup Service叫做Launch Daemon和Launch Agents 。而视为Service的程序,就该是Background Process,不应该提供GUI,也不应该跳到(Console的)Foreground 。当然有些例外,例如听快速键之后跳出视窗的程序。

    Launchd管理的Background Process有四种:

    1. Launch Daemon:在开机时加载(Load)。
    2. Launch Agent:在使用者登录时加载。
    3. XPC Service:好像是10.7才有的。
    4. Login Items:在User登录时执行。有两种方法可以用程序新增项目到Login Item:(Shared File List:会出现在Account偏好设定的Login Item清单。Service Management Framework:这个就不会出现在Login Item清单。)

    (以下把重点放在Launch Daemon/Agent 。至于XPC和Login Item先不做解释。)

    Launch Daemon & Launch Agent

    Launch Daemon和Launch Agent是同一种东西在不同Scopes的异名。Launch Daemon是System-Wide(系统级别)的Service,称为Daemon,Launch Agent是Per-User(用户级别)的Service ,称为Agent,前者在开机时会加载(Load),后者在使用者登录时(才)会加载。

    如果你打开Activity Monitor,并切换到Hierarchy View,你会发现有个Launchd会在最上层,跟它同层的只有kernel_task,它下面有很多Child Processes的User都是root,其中还有一个Launchd,启动的User是你自己,它底下的Child Processes的User也几乎都是你自己。当这些Processes是由Launchd加载Launchd Property List File来执行的时候,前者由root执行的称为Launch Daemons,后者由使用者执行的称为Launch Agents 。

    Launchd Property List File就是你会在LaunchDaemon或LaunchAgents目录中看到的*.plist档案(以下统称plist档)。它是XML格式。

    launchd Service Process Lifecycle

    由Launchd所管理的Services(Launch Daemon、Launch Agent)是要先由Launchd加载(load)以后才会执行(run),但加载之后并不一定马上执行。在苹果的官方文件说明了kernel加载完成后会发生的事,用来说明Launch Daemons、Launch Agents及其Processes的生命周期。

    开机时,会先加载OS Kernel,加载完成后就执行Launchd,用来加载System-Wide Services(Daemons)。这个System-Wide Launchd在开机时会做这些事:

    1. 加载(load)存放在这些目录下的plist:(/System/Library/LaunchDaemons,/Library/LaunchDaemons)
    2. 注册那些plist里面设定的sockets(port)和file descriptors
    3. 执行(run)KeepAlive = true的Daemons,当然RunAtLoad = true的也会启动。

    Run好后,Loginwindow就出现了,提示使用者登录。有设定自动登录的话,就会跳过这关。

    在使用者登录以后,会执行属于该使用者的Launchd,负责处理Launch Agent,做的事跟上面加载Launch Daemon很像,差别在于它从以下的目录加载plist:

    • /System/Library/LaunchAgents
    • /Library/LaunchAgents
    • ~/Library/LaunchAgents

    由使用者执行的任何程序也都是Launchd来执行的,所以Launchd也是该使用者的所有Processes之母。

    在使用者登出、关机或重新开机时,会触发Termination Event。接受登出、关机、重新开机使用者指令的Process是Loginwindow。它会先向使用者确认,一但确认,就会对每个由该使用者的Launchd所启动的Processes送出Termination Signal,如果是Cocoa则送出Cocoa API的Event,其他的就送出SIGTERM要他们自我了断,45秒之后,除了Cocoa的应用程式可以丢出某个Error来取消这整个Termination Process,其他还没结束的都会被kill掉。

    这就是为什么Loginwindow这个Process会一直存在,它要负责把该使用者执行起来的Processes统统清掉。而Per-User Services都关掉以后,就回到Loginwindow,或是执行关机、重新开机的流程,后两者就是照着差不多的流程去关掉所有System-Wide Services。

    Launchd-Compatible Daemon Programming Guide

    以下是该文件中提及关于配合Launchd开发Daemon时应注意的事,提到关于plist的key就请参考man 5 launchd.plist。以下的Daemon指的是Launch Daemon所要运行的Process,所以Launch Agent也一并适用。

    Listen to SIGTERM

    如上文所提及的,由于Loginwindow这个Process在要关掉你的Daemon时会先送SIGTERM,要你自我了断,等太久没关掉才会SIGKILL。如果你的程式需要在结束之前做什么事,一定要听SIGTERM这个Signal。

    On-Demand Daemon

    Launch Daemon/Agent默认不会让某个Process一直执行,当它的设定没有KeepAlive = true时,它会根据被执行的Process的CPU Usage和Requests(如TCP/IP Service)来决定要不要送出SIGTERM叫他自尽。

    当该Service需要被使用时,而相对应的Program没有跑成Process时,会自动把该Service给跑起来。例如某个TCP/IP Service听某个Port,当这个Port有封包进来时,Launchd会把相对应的Service给启动,这种行为叫做on-demand 。

    当然,也有non-on-demand daemon,其实也就是keep-alive daemon,这也是传统意义上的Daemon ,比如一直躲在墙角默默执行,直到有人找他,他才跳出来回一下话,回完了以后又继续躲在墙角。只要把KeepAlive这个key设成true,它就会在plist被Launchd加载(load)时执行(run)起来。要是那个Process死掉,Launchd会知道,马上再把它开起来。所以如果你试着去Activity Monitor砍掉这种Daemon,它就马上会复活。

    No fork or exec

    传统的System Programming会教你用exec、fork等等的POSIX API来做Daemon,但配合Launchd时,由于Daemon的生命周期是由Launchd来控制的,除非强制要求Kepp-Alive,否则要生要死是Launchd决定,更何况Keep-Alive还要考虑Daemon Process在结束以后自动重新执行,所以在配合Launchd写Daemon时,苹果建议你不要用传统的fork和exec*。当然,plist文件中的ProgramArguments就是exec*系列subroutine的参数。

    当一个Process跑起来10秒内就死掉,Launchd会判定为Crash,然后试着重新执行。要是你用传统的fork-exec style,就可能会造成无限循环。

    No setuid / setgid / chroot / chdir etc

    为了安全性的考虑,苹果强烈建议你不要自己调用setupd、setgid、chroot、chdir等等System Subroutines,而是透过plist文件的设定值来让Launchd帮你完成,参考UserName、GroupName、RootDirectory、WorkingDirectory的keys 。

    No pipe redirection hell for fd 0, 1 or 2

    在写Log或输出信息时可以设定StandardOutPath、StandardErrorPath,只管输出到stdout或stderr就好了。而StandardInPath也可以让你的Process一执行就从stdin指定path的内容。也就是说,Launchd帮你把fd = 0, 1, 2的东西都传了一遍。

    其他应用

    定时任务

    Launch Daemon/Agent的设置项可以指定该Service的执行周期及执行时间,也就是说,它可以替代传统的at、periodic和cron。这些设定值的key请参考StartInterval和StartCalendarInterval。

    搭配LaunchOnlyOnce的话可以模拟at,但如果要用Launchd只临时做一件事,还不如直接at方便。

    监视文件或目录异动

    Launch Daemon/Agent可以监视某个path的异动,设定在WatchPaths这个key。这里所说的path可以是Directory或是某个特定的文件,只要该path有异动,就会执行你的Job。

    也可以用来清Queue,只要Directory里面有东西,就会执行Job直到空为止,可以用来做Mail Server或Notification。设定在QueueDirectories这个key。

     

    参考:

    https://en.wikipedia.org/wiki/Init

    https://en.wikipedia.org/wiki/Launchd

    https://stackoverflow.com/questions/15735320/osx-s-etc-init-d-equivalent

    https://nathangrigg.com/2012/07/schedule-jobs-using-launchd#launchctl

    https://blog.yorkxin.org/2011/08/04/osx-launch-daemon-agent(以上内容转自此篇博客,由于繁体翻译成简体,有些地方可能语义存在问题)

    https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html

    https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/launchctl.1.html

    https://developer.apple.com/library/content/technotes/tn2083/_index.html

    转载于:https://www.cnblogs.com/EasonJim/p/7173841.html

    展开全文
  • launchd守护进程

    千次阅读 2016-04-21 21:16:40
    1. launchd mac系统下通用的进程管理器,是mac系统下非常重要的一个进程,一般来说该进程不允许直接以命令行的形式调用。只能通过其控制管理界面,launchctl来进行控制。...launchd主要功能
  • openlaunchd, 非达尔文系统的launchd(8) 端口 打开 LaunchdMac OS X 10.4 Tiger引入了一个名为 launchd的新程序。 守护进程替换了 SystemStarter ( macOS legacy ) 和旧 rc.d ( BSD legacy ) 启动进程和作业
  • 2、设置launchd cd ~/Library/LaunchAgents #当前用户 cd /Library/LaunchAgents #所有用户 vi com.river.agent.plist #创建文件,内容如下 com.river.agent.plist内容 <!DOCTYPE plist PUBLIC "-//...
  • localhost com.apple.xpc.launchd[1] (com.apple.opendirectoryd): Unknown key for Boolean: BeginTransactionAtShutdown 与 localhost com.apple.xpc.launchd[1] (org.cups.cupsd): Service has increased ...
  • https://en.wikipedia.org/wiki/Launchd(plist语法参考) Mac 10.12通过Launchd创建自定义服务(基于MySQL 5.7.15的开机自启动) 标签:dia doctype 操作 启动 ack tar array plist dtd 本条技术文章来源于...
  • Mac下用Launchd实现执行开机启动命令

    千次阅读 2018-11-15 17:30:39
    实现步骤: 1.进入/Library/LaunchDaemons目录 cd /Library/LaunchDaemons 2.创建一个plist文件 sudo vim local.localhost.startup.plist 复制一下内容到文件并保存 ...DOCTYPE plist ...
  • 运行MinGw 根据文件安装位置输入命令 /c/Users/user/src/veins-3.0/sumo-launchd.py -vv - c /c/Users/user/sr...
  • http://kenwublog.com/mac-os-launchd-tuningMac下的启动服务主要有三个地方可配置:1,系统偏好设置->帐户->登陆项2,/System/...前两种优化比较简单,本文主要介绍的是第三种更为复杂的launchd配置优化。launchd
  • "Mac系统的launchd守护进程daemon2013笔记整理": 关键词:mac 系统 launchd 守护 进程 daemon2013 笔记 整理 1. launchd mac系统下通用的进程管理器,是mac系统下非常重要的一个进程,...
  • Mac OS Launchd 启动服务详解

    千次阅读 2015-10-15 17:31:06
    Mac下的启动服务主要有三个地方可配置...3,launchd 系统初始化进程配置。 前两种优化比较简单,本文主要介绍的是第三种更为复杂的launchd配置优化。 launchd是Mac OS下,用于初始化系统环境的关键进程。类似Linux
  • 利用mac的launchd开机后定时启动shell脚本 shell脚本 mac开机启动 概念 配置Mac开机后定时启动 参考文档利用mac的launchd,开机后定时启动shell脚本 利用mac os x的launchd,开机后定时启动shell脚本,并且周期执行...
  • Launchd进程简介 苹果Mac OS X系统上,第一个进程是kernel_task ------ 内核进程(这个完全不同于Linux系统),PID为0;第二个进程是launchd(相当于linux的init进程),PID为1。 可以把kernel_task当作第0个...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,302
精华内容 1,320
关键字:

launchd

友情链接: core-decrease.rar